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

@Component({
    selector: 'app-list',
    templateUrl: './list.component.html',
    styleUrls: ['./list.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class ListComponent extends BaseList implements OnInit, OnChanges {
    @Input() counterOnlineList: any = [];
    @Output() onEdit = new EventEmitter()
    @Output() onDelete = new EventEmitter()
    constructor(
        private swSV: SweetalertService,
        private counterOnlineSV: OnlineCountersService
    ) {
        super()
    }

    ngOnInit(): void {
    }

    ngOnChanges(): void {
        this.counterOnlineList = this.updateMatTable(this.counterOnlineList ? this.counterOnlineList : [])
    }

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