import { OnInit, OnDestroy, Component, ViewEncapsulation, TemplateRef } from "@angular/core";
import { takeUntil, finalize } from "rxjs/operators";
import { IUserAccount, Page } from "../../../../../shared/models";
import { AppData } from "../../../../../app.data";
import { NgbModalRef, NgbModal } from "@ng-bootstrap/ng-bootstrap";
import { AppointmentTypes } from "../../../../../shared/entities/appoinment-types.entity";
import { FormGroup, FormBuilder, Validators } from "@angular/forms";
import { ApiResources } from "../../../../../shared/helpers";
import { HttpService, NotifyService } from "../../../../../shared/services";
import { WhiteSpaceValidator } from "../../../../../shared/validators";

class ColorTemplate {
    colorPalate: string;
}
@Component({
    templateUrl: "./appointment-types.html",
    encapsulation: ViewEncapsulation.None
})

export class AppointmentTypePage implements OnInit, OnDestroy {

    page: Page;
    modalRef: NgbModalRef;
    submitting: boolean;
    submitted: boolean;
    colorPalates: Array<ColorTemplate>;
    loading: boolean;
    appointmentTypeForm: FormGroup;
    records: Array<AppointmentTypes>;



    constructor(
        private readonly appData: AppData,
        private readonly formBuilder: FormBuilder,
        private readonly httpService: HttpService,
        private readonly modalService: NgbModal,
        private readonly notifyService: NotifyService    )
    {
        this.page = new Page();
        this.colorPalates = new Array<ColorTemplate>();
        this.records = new Array<AppointmentTypes>();

    }
    fetchAppointmentTypes() {
        this.loading = true;
        const request = {};
        this.httpService.post(ApiResources.getURI(ApiResources.appointmentTypes.base, ApiResources.appointmentTypes.fetch), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loading = false))
            .subscribe(
                (response: Array<AppointmentTypes>) => {
                    this.records = response;
                },
            );
    }
    onSubmit() {
        this.submitted = true;
        if (this.appointmentTypeForm.invalid) {
            return;
        }
        this.submitting = true;
        const request = {
            ...this.appointmentTypeForm.getRawValue(),
            createdBy: this.page.userAccount.accountId,
            createdByName: this.page.userAccount.fullName,
        };

        let url = ApiResources.getURI(ApiResources.appointmentTypes.base, ApiResources.appointmentTypes.insert);
        if (request["appointmentTypeId"] > 0) {
            url = ApiResources.getURI(ApiResources.appointmentTypes.base, ApiResources.appointmentTypes.update);
        }
        this.httpService.post(url, request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.submitted = this.submitting = false))
            .subscribe(
                (response: number) => {
                    if (response > 0) {
                        this.notifyService.successToast(`Record ${request["appointmentTypeId"] > 0 ? 'updated' : 'added'} successfully.`);
                    }
                    if (response === -1) {
                        this.notifyService.warningToast("This Appointment Type already exists.");
                        return;
                    }
                    this.onCloseModal();
                    this.fetchAppointmentTypes();
                },
            );
    }
    onDelete(record: AppointmentTypes) {
        this.notifyService.delete(() => {
            const request = {
                appointmentTypeId: record.appointmentTypeId,
                name: record.name,
                createdBy: this.page.userAccount.accountId,
                createdByName: this.page.userAccount.fullName,
            };
            this.httpService.post(ApiResources.getURI(ApiResources.appointmentTypes.base, ApiResources.appointmentTypes.delete), request)
                .pipe(takeUntil(this.page.unSubscribe))
                .pipe(finalize(() => this.loading = false))
                .subscribe(
                    (response: number) => {
                        if (response > 0) {
                            this.notifyService.successToast("Record deleted successfully.");
                        }
                        if (response === -3) {
                            this.notifyService.warningToast("The record you tried to delete can't be deleted because it is being used.");
                        }
                        this.fetchAppointmentTypes();
                    },
                    
                );
        })
    }
    private buildColorPalates() {
        ["#ffd2d2", "#d9d4ff", "#d2e5ff", "#f3f7f9", "#F8E5B4", "#d4ffef", "#daffff", "#ffdbff", "#CFFFC2", "#E4E6E8"].forEach((color) => {
            const paltaes = new ColorTemplate();
            paltaes.colorPalate = color;
            this.colorPalates.push(paltaes)
        }); 
    }
    private buildForm() {
        this.buildColorPalates();
        this.appointmentTypeForm = this.formBuilder.group({
            appointmentTypeId: 0,
            name: [null, [Validators.required, Validators.maxLength(250), WhiteSpaceValidator.isValid]],
            rowColor: ["#FFFFFF"]
        });
    }
    onOpenModel(content: TemplateRef<any>, record?: AppointmentTypes) {
        this.buildForm();
        if (record) {
            this.appointmentTypeForm.patchValue({
                appointmentTypeId: record.appointmentTypeId,
                name: record.name,
                rowColor: record.rowColor
            });
        }
        this.modalRef = this.modalService.open(content, {
            backdrop: "static",
            keyboard: false,
            centered: false,
            windowClass: "custom-modal effect-scale"
        });
    }
    get form() { return this.appointmentTypeForm.controls; }
    onCloseModal() {
        try {
            this.modalRef.close();
            this.modalRef = undefined;
        } catch (e) {
            // ignored;
        }

        this.loading = false;
        this.submitting = undefined;
        this.submitted = undefined;
        this.colorPalates = new Array<ColorTemplate>();
    }
    selectColorOption(color: string) {
        this.appointmentTypeForm.patchValue({
            rowColor: color
        });
    }
    ngOnDestroy() {
        this.onCloseModal();
        this.page.unsubscribeAll()
    }
    ngOnInit() {
        this.appData.userAccount
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((userAccount: IUserAccount) => {
                if (userAccount) {
                    this.page.userAccount = userAccount;
                    this.fetchAppointmentTypes();
                } else {
                    this.page.userAccount = undefined;
                }
            });
    }

}