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

@Component({
    selector: 'app-testing-field-list',
    templateUrl: './testing-field-list.component.html',
    styleUrls: ['./testing-field-list.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class TestingFieldListComponent extends BaseList implements OnInit , OnChanges {
    @Input() branchsList: any = [];
    @Output() edit = new EventEmitter();
    @Output() delete = new EventEmitter();
    column = ['0','1', '2', 'default', '3', '4', '5', '6'];
    constructor(
        private swSV: SweetalertService,
        private testingfieldSV: TestingFieldService,
    ) {
        super();
    }

    ngOnInit(): void {
    }

    ngOnChanges(){
        this.branchsList = this.updateMatTable(this.branchsList);
    }

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

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

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

}
