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

@Component({
    selector: 'app-education-type-dialog',
    templateUrl: './education-type-dialog.component.html',
    styleUrls: ['./education-type-dialog.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class EducationTypeDialogComponent implements OnInit {
    form;
    statusMock = [{id: 1, name: 'ใช้งาน'}, {id: 2, name: 'ยกเลิก'}];
    constructor(
        private    eductypeSV: EducationTypesService,
        private fb: FormBuilder,
        private swSV: SweetalertService,
        private dialogRef: MatDialogRef<EducationTypeDialogComponent>,
        @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,
            education_type_uid: null,
            education_type_code: null,
            education_type_name_th: null,
            education_type_name_en: null
        });
    }

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

    save(){
        const form = this.form.getRawValue();
        // form.education_type_name_th = form.education_type_code;
        // form.education_type_name_en = form.education_type_code;
        if (this.data){
            this.eductypeSV.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.eductypeSV.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();
    }

}
