import {Component, OnInit, ChangeDetectionStrategy, Inject} from '@angular/core';
import {FormBuilder} from '@angular/forms';
import {MatDialogRef, MAT_DIALOG_DATA} from '@angular/material/dialog';
import {throwError} from 'rxjs';
import {catchError, tap} from 'rxjs/operators';
import {CalendarTypeService} from 'src/app/core/service/settings/calendar-type.service';
import {SweetalertService} from 'src/app/core/service/sweetalert/sweetalert';

@Component({
    selector: 'app-calendar-dialog',
    templateUrl: './calendar-dialog.component.html',
    styleUrls: ['./calendar-dialog.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class CalendarDialogComponent implements OnInit {
    form;
    statusMock = [{id: 1, name: 'ใช้งาน'}, {id: 2, name: 'ยกเลิก'}]

    constructor(
        private fb: FormBuilder,
        private calendarSV: CalendarTypeService,
        private swSV: SweetalertService,
        private dialogRef: MatDialogRef<CalendarDialogComponent>,
        @Inject(MAT_DIALOG_DATA) public data
    ) {
        this.form = this.fb.group({
            status_id: 1,
            create_by: null,
            create_date: null,
            updated_by: null,
            updated_date: null,
            owner_agency_uid: null,
            calendar_type_uid: null,
            calendar_type_code: null,
            calendar_type_name_th: null,
            calendar_type_name_en: null
        });
    }

    ngOnInit(): void {
        if (this.data) {
            this.calendarSV.get(this.data).pipe(
                tap(x => this.form.patchValue(x))
            ).subscribe()
        }
    }

    save() {
        const form = this.form.getRawValue()
        if (this.data) {
            this.calendarSV.update2(form).pipe(
                tap(x => this.swSV.updateSuccess()),
                tap(x => this.dialogRef.close()),
                catchError(err => {
                    this.swSV.err()
                    this.dialogRef.close('err')
                    return throwError(err)
                })
            ).subscribe()
        } else {
            this.calendarSV.add(form).pipe(
                tap(x => this.swSV.saveSuccess()),
                tap(x => this.dialogRef.close()),
                catchError(err => {
                    this.swSV.err()
                    this.dialogRef.close()
                    return throwError(err)
                })
            ).subscribe()
        }
    }

    cancel() {
        this.dialogRef.close()
    }

}
