import {Component, OnInit, ChangeDetectionStrategy, Output, EventEmitter, OnChanges, ChangeDetectorRef, Input} from '@angular/core';
import {BaseList} from '../../../../../../core/base/base-list';
import {AppTokenService} from '../../../../../../core/service/security/app-token.service';
import {filter} from 'rxjs/internal/operators/filter';
import {concatMap, tap} from 'rxjs/operators';
import {forkJoin} from 'rxjs';
import {SweetalertService} from '../../../../../../core/service/sweetalert/sweetalert';
import {TestingVdosService} from '../../../../../../core/service/settings/testing-vdos.service';

@Component({
    selector: 'app-testing-vdos-list',
    templateUrl: './testing-vdos-list.component.html',
    styleUrls: ['./testing-vdos-list.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class TestingVdosListComponent extends BaseList implements OnInit, OnChanges {
    @Input() vdosList: any = [];
    @Output() edit = new EventEmitter();
    @Output() delete = new EventEmitter();

    column = [
        '1',
        'testing_vdo_code',
        'testing_vdo_name_th',
        'default',
        'vdo_name',
        'created_by',
        'created_datetime',
        '7'
    ];


    reload: boolean;

    constructor(
        private appTokenSV: AppTokenService,
        private cdr: ChangeDetectorRef,
        private swSV: SweetalertService,
        private testingVdosSV: TestingVdosService,

    ) {
        super();
    }

    ngOnInit(): void {
        this.reload = false;
        setTimeout(() => {
            this.reload = true;
            this.cdr.detectChanges();
        }, 5000);
    }

    ngOnChanges(){
        this.vdosList = this.updateMatTable(this.vdosList ? this.vdosList : []);
    }

    setDefault(event,i,self){
        event.preventDefault();
        this.swSV.confirm('ต้องการเปลี่ยนแปลงค่านี้ใช่หรือไม่').pipe(
            filter(x => x.isConfirmed),
            tap(x => {
                this.vdosList.data.map((vdo,index) => {
                    if(index == i){
                        vdo.is_default == true? vdo.is_default = false : vdo.is_default = true
                        self.checked = vdo.is_default
                    }else{
                        vdo.is_default = false
                    }
                })
            }),
            concatMap(x => {
                let updateData$ = this.vdosList.data.map(a => {
                    return this.testingVdosSV.update2(a)
                })
                return forkJoin(updateData$)
            }),
        ).subscribe()
    }

    onEdit(id){
        this.edit.emit(id);
    }

    onDelete(id){
        this.delete.emit(id);
    }

}
