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





@Component({
    templateUrl: "./add-ambulance.html",
    encapsulation: ViewEncapsulation.None
})
export class AddAmbulancePage implements OnInit, OnDestroy {
    page: Page;
    loading: boolean;
    ambulancerecords: Array<Ambulance>;
    submitting: boolean;
    submitted: boolean;
    ambulanceForm: FormGroup;
    modalRef: NgbModalRef;


    constructor(
        private readonly formBuilder: FormBuilder,
        private readonly modalService: NgbModal,
        private readonly appData: AppData,
        private readonly httpService: HttpService,
        private readonly notifyService: NotifyService
    ) {
        this.page = new Page();
        this.loading = true;
    }

    onSubmit() {
        this.submitted = true;
        if (this.ambulanceForm.invalid) {
            return;
        }
        this.submitting = true;
        const request = {
            ...this.ambulanceForm.getRawValue(),
            createdBy: this.page.userAccount.accountId,
            loginRoleId: this.page.userAccount.roleId,
            createdByName: this.page.userAccount.fullName
        };
        var url = ApiResources.getURI(ApiResources.ambulance.base, ApiResources.ambulance.insert);
        if (request["ambulanceId"] > 0) {
            url = ApiResources.getURI(ApiResources.ambulance.base, ApiResources.ambulance.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["ambulanceId"] > 0 ? 'updated' : 'added'} successfully.`);
                        this.fetchAmbulance();
                    }
                    if (response === -1) {
                        this.notifyService.warningToast("This ambulance No already exists.");
                        return;
                    }
                    this.onCloseModal();

                },

            );
    }

    fetchAmbulance() {
        this.loading = true;
        const request = {

        };
        this.httpService.post(ApiResources.getURI(ApiResources.ambulance.base, ApiResources.ambulance.fetch), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loading = false))
            .subscribe((responce: Array<Ambulance>) => {
                this.ambulancerecords = responce;
            });
    }

    //onDelete(record: Ambulance) {
    //    this.notifyService.delete(() => {
    //        const request = {
    //            ambulanceId: record.ambulanceId,
    //            ambulanceNo: record.ambulanceNo,
    //            createdBy: this.page.userAccount.accountId,
    //            loginRoleId: this.page.userAccount.roleId,
    //            createdByName: this.page.userAccount.fullName
    //        };
    //        this.httpService.post(ApiResources.getURI(ApiResources.ambulance.base, ApiResources.ambulance.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.fetchAmbulance();
    //                },
    //                //(error: HttpErrorResponse) => {
    //                //    this.onError(error)
    //                //}
    //            );
    //    })
    //}

    updateStatus(ambulance: Ambulance) {
        ambulance.modifiedBy = this.page.userAccount.accountId;
        this.httpService
            .put(ApiResources.getURI(ApiResources.ambulance.base, ApiResources.ambulance.modifyStatus), ambulance)
            .subscribe(() => {
                ambulance.active = !ambulance.active;
                this.fetchAmbulance();
            });
    }

    private buildForm() {
        this.ambulanceForm = this.formBuilder.group({
            ambulanceId: 0,
            ambulanceNo: [null, [Validators.required, Validators.maxLength(250), WhiteSpaceValidator.isValid]],
            assignedNo: [null, [Validators.required, Validators.maxLength(250), WhiteSpaceValidator.isValid]],
        })

    }

    onOpenModel(content: TemplateRef<any>, ambulanceRecord?: Ambulance) {
        this.buildForm();
        if (ambulanceRecord)
            this.ambulanceForm.patchValue({
                ambulanceId: ambulanceRecord.ambulanceId,
                ambulanceNo: ambulanceRecord.ambulanceNo,
                assignedNo: ambulanceRecord.assignedNo,
            });
        this.modalRef = this.modalService.open(content, {
            backdrop: "static",
            keyboard: false,
            centered: false,
            windowClass: "custom-modal effect-scale"
        });
    }

    get form() { return this.ambulanceForm.controls; }

    ngOnInit() {
        this.appData.userAccount
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((userAccount: IUserAccount) => {
                if (userAccount) {
                    this.page.userAccount = userAccount;
                    this.fetchAmbulance();
                } else {
                    this.page.userAccount = undefined;
                }
            });
    }
    ngOnDestroy() {
        this.page.unsubscribeAll();
    }

    onCloseModal() {
        try {
            this.modalRef.close();
            this.modalRef = undefined;
        } catch (e) {
            // ignored;
        }

        this.loading = false;
        this.submitting = undefined;
        this.submitted = undefined;
    }

}