import {Location} from '@angular/common';
import {Component, OnInit, ChangeDetectionStrategy, Inject, ChangeDetectorRef} from '@angular/core';
import {FormBuilder, FormGroup} from '@angular/forms';
import {MatDialogRef, MAT_DIALOG_DATA} from '@angular/material/dialog';
import {ActivatedRoute, Router} from '@angular/router';
import {throwError} from 'rxjs';
import {catchError, tap} from 'rxjs/operators';
import {BaseForm} from 'src/app/core/base/base-form';
import {OnlineCountersService} from 'src/app/core/service/settings/online-counters.service';
import {SweetalertService} from 'src/app/core/service/sweetalert/sweetalert';

@Component({
    selector: 'app-form-dialog',
    templateUrl: './form-dialog.component.html',
    styleUrls: ['./form-dialog.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class FormDialogComponent extends BaseForm implements OnInit {

    constructor(
        public router: Router,
        public fb: FormBuilder,
        public activeRoute: ActivatedRoute,
        public location: Location,
        public dialogRef: MatDialogRef<FormDialogComponent>,
        @Inject(MAT_DIALOG_DATA) public data,
        private onlineCounterSV: OnlineCountersService,
        private swSV: SweetalertService,
        private cdr: ChangeDetectorRef
    ) {
        super(router, activeRoute, fb, location)
    }

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

    createForm(): FormGroup {
        return this.fb.group({
            created_by: null,
            created_datetime: null,
            deleted_by: null,
            deleted_datetime: null,
            updated_by: null,
            updated_datetime: null,
            status_id: null,
            online_counter_uid: null,
            online_counter_code: null,
            online_counter_name_th: null,
            online_counter_name_en: null,
            is_default: null,
        })
    }

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


}
