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

@Component({
  selector: 'app-testcenter-list',
  templateUrl: './testcenter-list.component.html',
  styleUrls: ['./testcenter-list.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class TestcenterListComponent 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 branchservice: BranchService,
  ) {
    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.branchservice.update2(a)
        })
        return forkJoin(updateData$)
      }),
    ).subscribe()
  }

}
