import { Component, OnDestroy, OnInit, ViewEncapsulation, TemplateRef } from "@angular/core";
import { ApiResources, UtilHelper } from "@shared/helpers";
import { AppData, HttpService, NotifyService, ResourceService } from "@shared/services";
import { takeUntil, finalize } from "rxjs/operators";
import { NgbModal, NgbModalRef } from "@ng-bootstrap/ng-bootstrap";
import { FormGroup, Validators, FormBuilder } from "@angular/forms";
import { Page, IUserAccount, IResource, Pagination } from "@shared/models";
import { WhiteSpaceValidator } from "@shared/validators";
import { HttpErrorResponse } from "@angular/common/http";
import { EncounterOrderTemplatesList } from "../../../../../shared/entities/encounter-order-templates.entity";
import * as ClassicEditor from "@ckeditor/ckeditor5-build-classic";


@Component({
    templateUrl: "./encounter-order-templates.html",
    encapsulation: ViewEncapsulation.None
})
export class EncounterOrderTemplatesPage implements OnInit, OnDestroy {

    page: Page;
    modalRef: NgbModalRef;
    encounterOrderTemplateForm: FormGroup;
    submitting: boolean;
    submitted: boolean;
    pagination: Pagination;
    loading: boolean;
    encounterType: IResource[];
    notesEditor = ClassicEditor;
    config = {
        placeholder: "Enter method text here!",
        toolbar: ["heading", "|", "bold", "italic", "link", "bulletedList", "numberedList", "blockQuote"]
    };
    encounterOrderTemplatesdata: Array<EncounterOrderTemplatesList>;


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

    }
    private fetchEncounterType() {
        this.resourceService.encounterType()
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((response: Array<IResource>) => {
                this.encounterType = response;
            });
    }
    private buildForm() {
        this.encounterOrderTemplateForm = this.formBuilder.group({
            encounterTemplateId :0,
            encounterTypeId: null,
            templateName: [null, [Validators.required, WhiteSpaceValidator.isValid]],
            description: [null, [Validators.required, WhiteSpaceValidator.isValid]]
        });
    }

    constructor(
        private readonly appData: AppData,
        private readonly modalService: NgbModal,
        private readonly formBuilder: FormBuilder,
        private readonly notifyService: NotifyService,
        private readonly httpService: HttpService,
        private readonly resourceService: ResourceService
    ) {
        this.loading = true;
        this.page = new Page();
        this.initPagination();
    }
    private initPagination() {
        this.pagination = new Pagination();
        this.pagination.pageIndex = 1;
        this.pagination.pageSize = 10;

    }


    onNextPage() {
        $("body,html").animate({ scrollTop: 0 });
        this.fetch();
    }

    fetch() {
        this.loading = true;
        const request = {
            ...this.pagination
        };
        this.httpService
            .post<Array<EncounterOrderTemplatesList>>(ApiResources.getURI(ApiResources.orders.base, ApiResources.orders.fetchencounterOrderTemplates), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loading = false))
            .subscribe(
                (response: Array<EncounterOrderTemplatesList>) => {
                    this.encounterOrderTemplatesdata = response;
                    UtilHelper.applyPagination(this.encounterOrderTemplatesdata, this.pagination);
                },
                () => {
                    this.encounterOrderTemplatesdata = [];
                }
            );
    }


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

    onChangeEncounter(event: IResource) {
        this.encounterOrderTemplateForm.patchValue({
            encounterTypeId: event.id
        })
    }


    onSubmit() {
        this.submitted = true;
        if (this.encounterOrderTemplateForm.invalid) {
            return
        }
        this.submitting = true;
        this.loading = true;
        const request = Object.assign(UtilHelper.clone(this.encounterOrderTemplateForm.getRawValue()));
        if (this.encounterOrderTemplateForm.value.encounterTemplateId === 0) {
            request["createdBy"] = this.page.userAccount.accountId;
            request["createdByName"] = this.page.userAccount.fullName;
            this.httpService.post(ApiResources.getURI(ApiResources.orders.base, ApiResources.orders.modifyencounterOrderTemplates), request)
                .pipe(takeUntil(this.page.unSubscribe))
                .pipe(finalize(() => {
                    this.submitting = false;
                    this.submitted = false;
                    this.loading = false;
                }))
                .subscribe((response: number) => {
                    if (response > 0) {
                        this.fetch();
                        this.onCloseModal();
                        this.notifyService.successToast("EncounterOrderTemplate has been added successfully.");
                    }
                    else if (response == -1) {
                        this.notifyService.warningToast("This EncounterOrderTemplate is Not Added");
                    }
                    else if (response == -2) {
                        this.notifyService.warningToast("This EncounterOrderTemplate is Already Existed");
                    }

                }, (error: HttpErrorResponse) => {
                    const errorMessage = UtilHelper.handleError(error);
                    if (errorMessage) {
                        this.notifyService.warning(errorMessage);
                    } else {
                        this.notifyService.defaultError();
                    }
                });

        } else {

            if (this.encounterOrderTemplateForm.invalid) {
                return
            }
            request.modifiedBy = this.page.userAccount.accountId;
            request['active'] = this.encounterOrderTemplateForm.value.active;
            request["modifiedBy"] = this.page.userAccount.accountId;
            request["modifiedByName"] = this.page.userAccount.fullName;
            this.httpService.post(ApiResources.getURI(ApiResources.orders.base, ApiResources.orders.modifyencounterOrderTemplates), request)
                .pipe(takeUntil(this.page.unSubscribe))
                .pipe(finalize(() => {
                    this.submitting = false;
                    this.submitted = false;
                    this.loading = false;
                }))
                .subscribe((response: number) => {
                    if (response > 0) {
                        this.fetch();
                        this.onCloseModal();
                        this.notifyService.successToast("EncounterOrderTemplate has been Updated successfully.");
                    }
                    else if (response == -1) {
                        this.notifyService.warningToast("This EncounterOrderTemplate is Not Updated");
                    }
                    else if (response == -2) {
                        this.notifyService.warningToast("This EncounterOrderTemplate is Already Existed");
                    }

                }, (error: HttpErrorResponse) => {
                    const errorMessage = UtilHelper.handleError(error);
                    if (errorMessage) {
                        this.notifyService.warning(errorMessage);
                    } else {
                        this.notifyService.defaultError();
                    }
                });
        }
    }

    onApplyFilters() {
        this.loading = true;
        this.initPagination();
        this.fetch()
    }
    onResetFilters() {

        this.loading = true;
        this.initPagination();
        this.fetch()
    }

    onOpenModel(content: TemplateRef<any>, EncounterOrderTemplate?: EncounterOrderTemplatesList) {
        this.buildForm();
        if (EncounterOrderTemplate) {
            this.encounterOrderTemplateForm.patchValue({
                encounterTemplateId: EncounterOrderTemplate.encounterTemplateId,
                encounterTypeId: EncounterOrderTemplate.encounterTypeId,
                templateName: EncounterOrderTemplate.templateName,
                description: EncounterOrderTemplate.description
            })
        }
        this.modalRef = this.modalService.open(content, {
            backdrop: "static",
            keyboard: false,
            centered: true,
            windowClass: "custom-modal effect-scale"
        });
    }

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

    onChangeStatus(data: EncounterOrderTemplatesList) {
        this.notifyService.confirm(`You want to ${data.active ? 'Deactivate' : 'Activate'} this EncounterOrder Templates?`, () => {

            data["modifiedBy"] = this.page.userAccount.accountId;
            this.httpService.post(ApiResources.getURI(ApiResources.orders.base, ApiResources.orders.changestatusencounterOrderTemplates), data)
                .pipe(takeUntil(this.page.unSubscribe))
                .pipe(finalize(() => { this.loading = false }))
                .subscribe((response: number) => {
                    if (response > 0) {
                        this.notifyService.successToast(`${data.active ? 'Deactivate' : 'Activate'} successfully.`);
                    }
                    this.fetch();
                    this.onCloseModal();
                }, (error: HttpErrorResponse) => {
                    this.notifyService.errorToast(error.error);
                });
        });
    }

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

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

