import { Component, ViewEncapsulation, OnInit, OnDestroy, TemplateRef } from "@angular/core";
import { Page, IUserAccount } from "@shared/models";
import { AppData, HttpService, NotifyService } from "@shared/services";
import { takeUntil, finalize } from "rxjs/operators";
import * as ClassicEditor from "@ckeditor/ckeditor5-build-classic";
import { ApiResources, UtilHelper } from "@shared/helpers";
import { DynamicTemplate } from "@shared/entities";
import { NgbModalRef, NgbModal } from "@ng-bootstrap/ng-bootstrap";
import { HttpErrorResponse } from "@angular/common/http";

@Component({
    templateUrl: "./dynamic-template.html",
    encapsulation: ViewEncapsulation.None
})
export class DynamicTemplatePage implements OnInit, OnDestroy {
    page: Page;
    submitting: boolean;
    submitted: boolean;
    notesEditor = ClassicEditor;
    rawData = ["CC", "HPI", "Vitals", "History", "ROS", "Physical", "Diagnosis", "Patient", "Provider", "Location"]
    textVariable: [];
    htmlData: string;
    template: Array<DynamicTemplate>;
    loading: boolean;
    modalRef: NgbModalRef;
    templateName: string;
    dynamicTemplateId: number;

    constructor(
        private readonly appData: AppData,
        private readonly httpService: HttpService,
        private readonly notifyService: NotifyService,
        private readonly modalService: NgbModal

    ) {
        this.page = new Page();
        this.template = new Array<DynamicTemplate>();
    }

    bindData(value: any) {
        this.htmlData = (this.htmlData || '') + '<span id="dynamic-word">' + value + '</span>' + ' ';

    }

    private onError(error: HttpErrorResponse) {
        if (error) {
            this.notifyService.errorToast(UtilHelper.handleError(error));
        }
    }
    fetchTemplate() {
        this.loading = true;
        const request = {};
        this.httpService
            .post(ApiResources.getURI(ApiResources.dynamicTemplate.base, ApiResources.dynamicTemplate.fetch), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loading = false))
            .subscribe((response: Array<DynamicTemplate>) => {
                this.template = response;
            }, () => {
                this.notifyService.error("Error occured in fetching Template.");
            }
            );
    }
    onSubmit() {
        this.submitted = true;
        if (this.templateName === "" || this.templateName === undefined || this.templateName === null || this.templateName.trim() === "") {
            this.notifyService.warning("Template name is required.");
            return;
        }
        if (this.htmlData === "" || this.htmlData === undefined || this.htmlData === null || this.htmlData.trim() === "") {
            this.notifyService.warning("Template data is required.");
            return;
        }
        const request = Object.assign(UtilHelper.clone({ templateName: this.templateName, dynamicTemplateId: this.dynamicTemplateId, value: this.htmlData, createdBy: this.page.userAccount.accountId, createdByName: this.page.userAccount.fullName, loginRoleId: this.page.userAccount.roleId }));
        this.submitting = true
        var url = ApiResources.getURI(ApiResources.dynamicTemplate.base, ApiResources.dynamicTemplate.add);
        if (request["dynamicTemplateId"] > 0) {
            url = ApiResources.getURI(ApiResources.dynamicTemplate.base, ApiResources.dynamicTemplate.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["DynamicTemplateId"] > 0 ? 'updated' : 'added'} successfully.`);
                    }
                    if (response === -1) {
                        this.notifyService.warningToast("This Template Name already exists.");
                        return;
                    }
                    this.onClose();
                    this.fetchTemplate();
                },
                (error: HttpErrorResponse) => {
                    this.onError(error);
                }
            );
    }
    onDeleteTemplate(item: DynamicTemplate) {
        this.notifyService.delete(() => {
            const request = {
                dynamicTemplateId: item.dynamicTemplateId,
                createdBy: this.page.userAccount.accountId,
                loginRoleId: this.page.userAccount.roleId,
                templateName: item.templateName,
                createdByName: this.page.userAccount.fullName,

            };
            this.httpService.post(ApiResources.getURI(ApiResources.dynamicTemplate.base, ApiResources.dynamicTemplate.delete), request)
                .pipe(takeUntil(this.page.unSubscribe))
                .pipe(finalize(() => {
                    this.loading = false;
                }))
                .subscribe((response: number) => {
                    if (response > 0) {
                        this.notifyService.successToast("Deleted successfully.");
                    }
                    this.fetchTemplate();
                }, () => {
                    this.notifyService.warning("This Template can't be deleted.");
                });
        });
    }

    onClose() {
        try {
            this.modalRef.close();
            this.modalRef = undefined;
            this.templateName = null;
            this.htmlData = null;
            this.dynamicTemplateId = 0;
        } catch (e) {
            // ignored;
        }
        this.submitted = this.submitting = false;
    }
    onOpenModel(content: TemplateRef<any>, item?: DynamicTemplate) {
        this.templateName = null;
        if (item) {
            this.templateName = item.templateName;
            this.htmlData = item.value;
            this.dynamicTemplateId = item.dynamicTemplateId
        }
        this.modalRef = this.modalService.open(content, {
            backdrop: "static",
            keyboard: false,
            centered: false,
            size: "lg",
            windowClass: "custom-modal effect-scale"
        });
    }
    ngOnInit() {
        this.appData.userAccount
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((account: IUserAccount) => {
                if (account) {
                    this.page.userAccount = account;
                    this.fetchTemplate();
                }
                else {
                    this.page.userAccount = undefined;
                }
            });
    }
    ngOnDestroy() {
        this.page.unsubscribeAll();
    }
}