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



@Component({
    templateUrl: "./receipt.html",
    encapsulation: ViewEncapsulation.None
})
export class AmbulanceReceiptPage {

  
    page: Page;
    loadingambulancereceipts: boolean;
    ambulancereceipts: Array<AmbulanceReceipt>;
    ambulancerecords: Array<IResource>;
    driverDetail: Array<IResource>;
    submitting: boolean;
    submitted: boolean;
    ambulanceReceiptForm: FormGroup;
    modalRef: NgbModalRef;
    loadingAmbulances: boolean;
    loadingDrivers: boolean;


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

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

                },

            );
    }

    fetchReceipt() {
        this.loadingambulancereceipts = true;
        const request = {

        };
        this.httpService.post(ApiResources.getURI(ApiResources.ambulanceReceipt.base, ApiResources.ambulanceReceipt.fetch), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loadingambulancereceipts = false))
            .subscribe((responce: Array<AmbulanceReceipt>) => {
                this.ambulancereceipts = responce;
            });
    }

    private fetchAmbulances() {
        this.loadingAmbulances = true;
        this.resourceService.ambulances()
            .pipe(finalize(() => { this.loadingAmbulances = false }))
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((response: Array<IResource>) => {
                this.ambulancerecords = response;
            });
    }

    private fetchDriverDetail() {
        this.loadingDrivers = true;
        this.resourceService.driversDetails()
            .pipe(finalize(() => { this.loadingDrivers = false }))
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((response: Array<IResource>) => {
                this.driverDetail = response;
            });
    }

    private buildForm() {
        this.ambulanceReceiptForm = this.formBuilder.group({
            ambulanceRecieptId: 0,
            recieptNo:[null],
            ambulanceId: [null, [Validators.required]],
            driverDetailId: [null, [Validators.required]],
            patientName: [null, [Validators.required, Validators.maxLength(250), WhiteSpaceValidator.isValid]],
            address: [null, [Validators.required, Validators.maxLength(250), WhiteSpaceValidator.isValid]],
            patientMobile: [null, [Validators.required, MobileValidator.isValid, WhiteSpaceValidator.isValid]],
            amount: [null, [Validators.required, Validators.maxLength(250), WhiteSpaceValidator.isValid]],
            fromLocation: [null, [Validators.required, Validators.maxLength(250), WhiteSpaceValidator.isValid]],
            toLocation: [null, [Validators.required, Validators.maxLength(250), WhiteSpaceValidator.isValid]],
        })

    }

    onOpenModel(content: TemplateRef<any>, ambulanceReceipt?: AmbulanceReceipt) {
        this.buildForm();

        if (ambulanceReceipt) {
            this.ambulanceReceiptForm.patchValue({
                ambulanceRecieptId: ambulanceReceipt.ambulanceRecieptId,
                recieptNo: ambulanceReceipt.recieptNo,
                ambulanceId: ambulanceReceipt.ambulanceId,
                driverDetailId: ambulanceReceipt.driverDetailId,
                patientName: ambulanceReceipt.patientName,
                address: ambulanceReceipt.address,
                patientMobile: ambulanceReceipt.patientMobile,
                amount: ambulanceReceipt.amount,
                fromLocation: ambulanceReceipt.fromLocation,
                toLocation: ambulanceReceipt.toLocation
            });

        }
       
        this.modalRef = this.modalService.open(content, {
            backdrop: "static",
            keyboard: false,
            centered: false,
            windowClass: "custom-modal effect-scale"
        });
    }

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

    ngOnInit() {
        this.appData.userAccount
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((userAccount: IUserAccount) => {
                if (userAccount) {
                    this.page.userAccount = userAccount;
                    this.fetchReceipt();
                    this.fetchAmbulances();
                    this.fetchDriverDetail();
                } else {
                    this.page.userAccount = undefined;
                }
            });
    }

    ngOnDestroy() {
        this.page.unsubscribeAll()
    }

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

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


}