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 { tap, catchError } from 'rxjs/operators';
import { AcademicSemesterService } from 'src/app/core/service/settings/academic-semester.service';
import { AcademicYearService } from 'src/app/core/service/settings/academic-year.service';
import { SweetalertService } from 'src/app/core/service/sweetalert/sweetalert';

@Component({
    selector: 'app-academic-semesters-dialog',
    templateUrl: './academic-semesters-dialog.component.html',
    styleUrls: ['./academic-semesters-dialog.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class AcademicSemestersDialogComponent implements OnInit {
    form;
    statusMock = [{id:1, name:'ใช้งาน'},{id:2, name:'ยกเลิก'}]
    constructor(
        private fb: FormBuilder,
        private swSV: SweetalertService,
        private dialogRef: MatDialogRef<AcademicSemestersDialogComponent>,
        private acdmSemSV: AcademicSemesterService,
        @Inject(MAT_DIALOG_DATA) public data
    ) {
        this.form = this.fb.group({
            status_id: 1,
            created_by: null,
            created_datetime: null,
            updated_by: null,
            updated_datetime: null,
            deleted_by: null,
            deleted_datetime: null,
            academic_semester_uid: null,
            academic_semester_code: null,
            academic_semester_name_th: null,
            academic_semester_name_en: null
        })
    }

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

    save(){
        const form = this.form.getRawValue()
        form.academic_semester_name_th = form.academic_semester_code
        form.academic_semester_name_en = form.academic_semester_code
        if(this.data){
            this.acdmSemSV.update2(form).pipe(
                tap(x => this.swSV.updateSuccess()),
                tap(x => this.dialogRef.close()),
                catchError(err => {
                    this.swSV.err()
                    this.dialogRef.close()
                    return throwError(err)
                })
            ).subscribe()
        } else {
            this.acdmSemSV.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()
    }

}
