import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { Observable } from 'rxjs';
import { concatMap, filter, tap } from 'rxjs/operators';
import { CalendarTypeService } from 'src/app/core/service/settings/calendar-type.service';
import { SweetalertService } from 'src/app/core/service/sweetalert/sweetalert';
import { CalendarDialogComponent } from '../../presenter/dialog/calendar-dialog/calendar-dialog.component';

@Component({
    selector: 'app-calendars',
    templateUrl: './calendars.container.html',
    styleUrls: ['./calendars.container.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class CalendarsContainer implements OnInit {
    calendarList$ = new Observable()
    constructor(
        private dialog: MatDialog,
        private calendarSV: CalendarTypeService,
        private cdr: ChangeDetectorRef,
        private swSV: SweetalertService
    ) { }

    ngOnInit(): void {
        this.calendarList$ = this.calendarSV.getAll()
    }

    add(){
        const dialogRef = this.dialog.open(CalendarDialogComponent, {
            width: '500px',
            height: '300px',
        });
        dialogRef.afterClosed().pipe(
            tap(x => this.calendarList$ = this.calendarSV.getAll()),
            tap(x => this.cdr.detectChanges())
        ).subscribe()
    }

    edit(id){
        const dialogRef = this.dialog.open(CalendarDialogComponent, {
            width: '500px',
            height: '300px',
            data: id
        });
        dialogRef.afterClosed().pipe(
            tap(x => this.calendarList$ = this.calendarSV.getAll()),
            tap(x => this.cdr.detectChanges())
        ).subscribe()
    }

    delete(id){
        this.swSV.confirm().pipe(
            filter(x => x.isConfirmed),
            concatMap(x => {
                return this.calendarSV.deleteData(id).pipe(
                    tap(x => this.swSV.removeSuccess()),
                    tap(x => this.calendarList$ = this.calendarSV.getAll()),
                    tap(x => this.cdr.detectChanges())
                )
            })
        ).subscribe()
    }

    search(query){
        if(query) return this.calendarList$ = this.calendarSV.search(`?${query}`)
        if(!query) return this.calendarList$ = this.calendarSV.getAll()
    }

}
