import { Component, ViewEncapsulation, OnInit, OnDestroy, TemplateRef } from "@angular/core";
import { Page, IUserAccount } 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 } from "../../../../../../shared/services";
import { takeUntil, finalize } from "rxjs/operators";
import { ApiResources } from "../../../../../../shared/helpers";
import { DriverDetails } from "../../../../../../shared/entities/ambulance/driver-details.entity";
import { WhiteSpaceValidator } from "../../../../../../shared/validators";
import { HttpErrorResponse } from "@angular/common/http";



@Component({
    templateUrl: "./driverDetail.html",
    encapsulation: ViewEncapsulation.None
})
export class DriverDetailPage implements OnInit, OnDestroy {

    page: Page;
    loading: boolean;
    driverDetails: Array<DriverDetails>;
    submitting: boolean;
    submitted: boolean;
    driverDetailForm: 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.driverDetailForm.invalid) {
            return;
        }
        this.submitting = true;
        const request = {
            ...this.driverDetailForm.getRawValue(),
            createdBy: this.page.userAccount.accountId,
            loginRoleId: this.page.userAccount.roleId,
            createdByName: this.page.userAccount.fullName
        };
        var url = ApiResources.getURI(ApiResources.driverDetail.base, ApiResources.driverDetail.insert);
        if (request["driverDetailId"] > 0) {
            url = ApiResources.getURI(ApiResources.driverDetail.base, ApiResources.driverDetail.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["driverDetailId"] > 0 ? 'updated' : 'added'} successfully.`);
                        this.fetchDriver();
                    }
                    if (response === -1) {
                        this.notifyService.warningToast("This driver name already exists.");
                        return;
                    }
                    this.onCloseModal();

                },

            );
    }

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

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

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

    updateStatus(driverDetail: DriverDetails) {
        driverDetail.modifiedBy = this.page.userAccount.accountId;
        this.httpService
            .put(ApiResources.getURI(ApiResources.driverDetail.base, ApiResources.driverDetail.modifyStatus), driverDetail)
            .subscribe((response: number) => {
                if (response > 0) {
                    this.notifyService.successToast(`${status ? 'Activated' : 'Deactivated'} successfully.`);
                }
                this.fetchDriver();
            }, (error: HttpErrorResponse) => {
                this.notifyService.errorToast(error.error);
            });
                
           
    }

    private buildForm() {
        this.driverDetailForm = this.formBuilder.group({
            driverDetailId: 0,
            driverDetailName: [null, [Validators.required, Validators.maxLength(250), WhiteSpaceValidator.isValid, Validators.pattern('^[a-zA-Z]*$')]],
            mobileNo: [null, [Validators.required, Validators.maxLength(250), WhiteSpaceValidator.isValid, Validators.pattern('^[0-9]*$')]],
            aadharNo: [null, [Validators.required, Validators.maxLength(12), WhiteSpaceValidator.isValid, Validators.pattern('^[0-9]*$')]],
            address: [null, [Validators.required, Validators.maxLength(250), WhiteSpaceValidator.isValid]],
            fromTime: [null, [Validators.required]],
            toTime: [null, [Validators.required]],
        })

    }

    onOpenModel(content: TemplateRef<any>, driverDetail?: DriverDetails) {
        this.buildForm();
        if (driverDetail)
            this.driverDetailForm.patchValue({
                driverDetailId: driverDetail.driverDetailId,
                driverDetailName: driverDetail.driverDetailName,
                mobileNo: driverDetail.mobileNo,
                aadharNo: driverDetail.aadharNo,
                address: driverDetail.address,
                fromTime: driverDetail.fromTime,
                toTime: driverDetail.toTime
            });
        this.modalRef = this.modalService.open(content, {
            backdrop: "static",
            keyboard: false,
            centered: false,
            windowClass: "custom-modal effect-scale"
        });
    }

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

    ngOnInit() {
        this.appData.userAccount
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((userAccount: IUserAccount) => {
                if (userAccount) {
                    this.page.userAccount = userAccount;
                    this.fetchDriver();
                } 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;
    }



}