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

@Component({
    selector: 'app-typesubject-dialog',
    templateUrl: './typesubject-dialog.component.html',
    styleUrls: ['./typesubject-dialog.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class TypesubjectDialogComponent implements OnInit {
    form;
    statusMock = [{id:1, name:'ใช้งาน'},{id:2, name:'ยกเลิก'}]
    constructor(
        private fb: FormBuilder,
        private subjecttypeSV: SubjectTypesService,
        private swSV: SweetalertService,
        private dialogRef: MatDialogRef<TypesubjectDialogComponent>,
        @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,
            subject_type_uid: null,
            subject_type_code: null,
            subject_type_name_th: null,
            subject_type_name_en: null,
        });
    }

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

    save(){
        const form = this.form.getRawValue();
        if(this.data){
            this.subjecttypeSV.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.subjecttypeSV.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();
    }

}
