import {Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef} from '@angular/core';
import {BaseForm, sortByProperty} from '../../../../../../core/base/base-form';
import {FormBuilder, Validators} from '@angular/forms';
import {ActivatedRoute, Router} from '@angular/router';
import {Location} from '@angular/common';
import {SweetalertService} from '../../../../../../core/service/sweetalert/sweetalert';
import {UserCountersService} from '../../../../../../core/service/permission/user-counters.service';
import {catchError, concatMap, filter, tap} from 'rxjs/operators';
import {UploadService} from '../../../../../../core/service/upload/upload.service';
import {throwError} from 'rxjs';
import {TestingVdosService} from '../../../../../../core/service/settings/testing-vdos.service';

@Component({
    selector: 'app-testing-vdos-form',
    templateUrl: './testing-vdos-form.component.html',
    styleUrls: ['./testing-vdos-form.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class TestingVdosFormComponent extends BaseForm implements OnInit {
    imageSrc: string;
    selectfile;
    constructor(
        public fb: FormBuilder,
        public router: Router,
        public activeRoute: ActivatedRoute,
        public location: Location,
        private swSV: SweetalertService,
        private cdr: ChangeDetectorRef,
        private uploadSV: UploadService,
        private testingVdosSV: TestingVdosService,
    ) {
        super(router,activeRoute,fb,location);
    }

    ngOnInit(): void {
        if(this.state === 'edit'){
            this.testingVdosSV.get(this.id).pipe(
                tap(x => this.setupForm(x)),
                tap(x => this.cdr.detectChanges())
            ).subscribe();
        }
    }

    setupForm(x){
        this.form.patchValue(x);
        this.imageSrc = x.vdo_url
    }

    createForm(){
        return this.fb.group({
            testing_vdo_uid: null,
            testing_vdo_code: [null, Validators.required],
            testing_vdo_name_th: [null, Validators.required],
            testing_vdo_name_en: [null, Validators.required],
            vdo_url: [null, Validators.required],
            vdo_name: [null, Validators.required],
            created_by: null,
            created_datetime: null,
            updated_by: null,
            updated_datetime: null,
            deleted_by: null,
            deleted_datetime: null,
        });
    }

    uploadVideo(event){
        const file = event.target.files[0];
        if(file.type.indexOf('image')> -1){
            return this.swSV.errText('กรุณาอัพโหลดไฟล์วิดีโอ')
        } else if(file.type.indexOf('video')> -1){
            this.selectfile = event.target.files[0];
            const formData: FormData = new FormData();
            formData.append('filecard', this.selectfile, this.selectfile.name);
            this.uploadSV.add(formData).pipe(
                tap((x: any) => this.form.get('vdo_url').setValue(x[0].file_name)),
                tap((x: any) => this.imageSrc = x[0].file_name),
                tap((x: any) => this.form.get('vdo_name').setValue(x[0].name)),
                tap(x => this.cdr.detectChanges()),
            ).subscribe();
        }
    }

    save(){
        const form = this.form.getRawValue();
        switch (this.state) {
            case 'edit':
                this.testingVdosSV.update2(form).pipe(
                    tap(x => this.swSV.updateSuccess()),
                    tap(x => window.history.back()),
                    catchError(err => {
                        this.swSV.errText(err.error);
                        return throwError(err);
                    })
                ).subscribe();
                break;

            case 'add':
                this.testingVdosSV.add(form).pipe(
                    tap(x => this.swSV.saveSuccess()),
                    tap(x => window.history.back()),
                    catchError(err => {
                        this.swSV.errText(err.error);
                        return throwError(err);
                    })
                ).subscribe();
                break;
        }
    }

}
