import { Component, OnDestroy, OnInit, ViewEncapsulation, TemplateRef } from "@angular/core";
import { AppData, HttpService, NotifyService } from "@shared/services";
import { takeUntil, finalize } from "rxjs/operators";
import { Page, IUserAccount } from "@shared/models";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { HttpErrorResponse } from "@angular/common/http";
import { ApiResources, UtilHelper } from "@shared/helpers";
import { NgbModalRef, NgbModal } from "@ng-bootstrap/ng-bootstrap";
import { ReferenceTypes } from "@shared/entities";

@Component({
    templateUrl: "./reference-types.html",
    encapsulation: ViewEncapsulation.None
})
export class ReferenceTypePage implements OnInit, OnDestroy {
    page: Page;
    loading: boolean;
    modalRef: NgbModalRef;
    submitted: boolean;
    submitting: boolean;
    moduleForm: FormGroup;
    references: Array<ReferenceTypes>;
    selectedModule: ReferenceTypes;

    constructor(
        private readonly appData: AppData,
        private readonly formBuilder: FormBuilder,
        private readonly modalService: NgbModal,
        private readonly httpService: HttpService,
        private readonly notifyService: NotifyService
    ) {
        this.page = new Page();
        this.references = new Array<ReferenceTypes>();
        this.selectedModule = new ReferenceTypes();
    }

    private buildForm() {
        this.moduleForm = this.formBuilder.group({
            patientReferredById: 0,
            name: [null, [Validators.required]],
            
        })
    }

    onOpenModel(content: TemplateRef<any>, module?: ReferenceTypes) {
        this.buildForm();
        if (module) {
            this.selectedModule = module;
            this.updateForm();
        }
        this.modalRef = this.modalService.open(content, {
            backdrop: "static",
            keyboard: false,
            centered: true,
            windowClass: "custom-modal effect-scale"
        });
    }

    private updateForm() {
        this.moduleForm.patchValue({
            patientReferredById: this.selectedModule.patientReferredById,
            name: this.selectedModule.name        
        });
    }

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

    private fetchAllReferences() {
        this.loading = true;
        const request = {};
        this.httpService.post<Array<ReferenceTypes>>(ApiResources.getURI(ApiResources.referenceTypes.base, ApiResources.referenceTypes.fetch), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loading = false))
            .subscribe((response: Array<ReferenceTypes>) => {
                this.references = response;
            });
    }

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


    onResetForm() {
        this.submitted = this.submitting = false;
        this.buildForm();
    }

    onSubmit() {
        this.submitted = true;
        if (!this.moduleForm.valid) {
            return;
        }
        
        this.submitting = true;

        const request = {
            ...this.moduleForm.getRawValue(),
            createdBy: this.page.userAccount.accountId,
            loginRoleId: this.page.userAccount.roleId,
            createdByName: this.page.userAccount.fullName
        }

        if (this.moduleForm.value.patientReferredById === 0) {
            request["createdBy"] = this.page.userAccount.accountId;
            this.httpService.post<number>(ApiResources.getURI(ApiResources.referenceTypes.base, ApiResources.referenceTypes.add), request)
                .pipe(takeUntil(this.page.unSubscribe))
                .pipe(finalize(() => {
                    this.submitting = false;
                    this.submitted = false;
                    this.page.loading = false;
                }))                
                .subscribe((response: number) => {
                    if (response > 0) {
                        this.notifyService.successToast(`Reference created successfully.`);
                    }
                    if (response === -1) {
                        this.notifyService.warningToast("This reference already exists.");
                    }
                    if (response === -2) {
                        this.notifyService.warningToast("Unable to update roles.");
                    }
                    this.onCloseModal();
                    this.fetchAllReferences();
                });
        }

        else {
            request.modifiedBy = this.page.userAccount.accountId;
            request["modifiedByName"] = this.page.userAccount.fullName;

            //delete request.type;
            this.httpService.post(ApiResources.getURI(ApiResources.referenceTypes.base, ApiResources.referenceTypes.update), request)
                .pipe(takeUntil(this.page.unSubscribe))
                .pipe(finalize(() => {
                    this.submitting = false;
                    this.submitted = false;
                }))
                .subscribe(() => {
                    this.onCloseModal();
                    this.fetchAllReferences();
                    this.notifyService.successToast("Module details has been updated successfully.");
                }, (error: HttpErrorResponse) => {
                    const errorMessage = UtilHelper.handleError(error);
                    if (errorMessage) {
                        this.notifyService.warningToast(errorMessage);
                    } else {
                        this.notifyService.defaultErrorToast();
                    }
                });
        }

    }

    onDelete(record: ReferenceTypes) {
        this.notifyService.confirm(
            `Are you sure to Delete <span class='font-weight-bold'>${record.name}</span>`,
            () => {               
                const request = {
                    patientReferredById: record.patientReferredById,
                    idProofName: record.name,
                    createdBy: this.page.userAccount.accountId,
                    loginRoleId: this.page.userAccount.roleId,
                    createdByName: this.page.userAccount.fullName
                };
                this.httpService
                    .post(ApiResources.getURI(ApiResources.referenceTypes.base, ApiResources.referenceTypes.delete), request)
                    .pipe(takeUntil(this.page.unSubscribe))
                    .subscribe(
                        () => {
                            this.notifyService.successToast("Module deleted successfully.");
                            this.fetchAllReferences();
                        },
                        () => {
                            this.notifyService.defaultErrorToast();
                        }
                    );
            }
        );
    }

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

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