import { Component, OnDestroy, OnInit, TemplateRef, HostListener, ViewChild } from "@angular/core";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { Router, NavigationEnd } from "@angular/router";
import { NgbModal, NgbModalRef, NgbTypeaheadSelectItemEvent } from "@ng-bootstrap/ng-bootstrap";
import { Observable, of, Subject, Subscription } from "rxjs";
import { takeUntil, finalize, debounceTime, distinctUntilChanged, tap, switchMap, catchError } from "rxjs/operators";
import { ApiResources, DateHelper, UtilHelper, LinqHelper } from "@shared/helpers";
//import { ApiResources, DateHelper, LocalStorageHelper, UtilHelper } from "@shared/helpers";
import { IUserAccount, Page, IResource, IUser, IMenuModel, HttpErrorType, ICategoryMenuModel, GenericResponse, GenericStatus, IMenuPatientModel, Pagination } from "@shared/models";
import { AppData, appUrls, HttpService, ResourceService, IdentityService, NotifyService, MenuService, HttpErrorService, SettingService, CommunicationService, JitsiService } from "@shared/services";
import { CompareValidator } from "@shared/validators";
import { Role, MenuType } from "@shared/enums";
import { AuditLog, Notification, ICubicle, Setting } from "@shared/entities";
import { NgSelectComponent } from "@ng-select/ng-select";
//import { DomSanitizer } from "@angular/platform-browser";
const CUBICLE_PAGE_SIZE = 5;

class Settings {
    providerId: number;
    theme: string = "light";
    enableEmailAlerts: boolean;
    enableSMSAlerts: boolean;
    enableDesktopNotifications: boolean;
    enableMobileNotifications: boolean;
}

class MenuHolder {
    menuName: string;
    menuUrl: string;
    mainPage: string;
    subMenus: Array<IMenuModel>;
}

//const firebaseConfig = {
//    apiKey: "AIzaSyD7BsM-9nNjTtceWLBBcmeB8rF57slhwmc",
//    authDomain: "airopd-patient.firebaseapp.com",
//    databaseURL: "https://airopd-patient.firebaseio.com",
//    projectId: "airopd-patient",
//    storageBucket: "airopd-patient.appspot.com",
//    messagingSenderId: "604641314293",
//    appId: "1:604641314293:web:e58639265aaa9c88f38cbc",
//    measurementId: "G-88RPR98C1W",
//    vapidKey: "BIPwrSGkeNlw-mUtBlFzlIMgA9N-Rks0Ay25viPjnGmJ03ZywrhtWGYysfpLOPBou8UIZvbg-7AE1rKhPa-9KFY"
//};

@Component({
    templateUrl: "./layout.html"
})
export class LayoutComponent implements OnInit, OnDestroy {
    @ViewChild("templateModify", { static: true }) templateModify: TemplateRef<any>;
    @ViewChild("templateCubicle", { static: false }) templateCubicle: TemplateRef<any>;
    today = DateHelper.ngbToday;
    minDate = DateHelper.minDate;
    page: Page;
    role = Role;
    menuType = MenuType;
    httpErrorType = HttpErrorType;
    selectedPatient: IResource;
    searching = false;
    searchFailed = false;
    auditlog: AuditLog;
    modalRef: NgbModalRef;
    changePasswordForm: FormGroup;
    submitting: boolean;
    submitted: boolean;
    settings: Settings;

    userForm: FormGroup;
    user: IUser;
    userLoading: boolean;


    loading: boolean;

    webVersion: string;
    menus: Array<IMenuModel>;
    allMenus: Array<IMenuModel>;
    allMenuAndSubMenu: Array<IMenuPatientModel>;
    menuHolder: MenuHolder;
    isHovering: boolean;
    defaultMenu: string;
    logCount: number = 0;
    isHitMenu: boolean;
    env: string;
    envTitle: string;
    activeRoute: string;
    logoSubscription: Subscription;
    logoBasics: Setting;//
    imageType: string;
    showTicket: boolean;
    notifications: Array<Notification>;
    assignedCubicles: Array<ICubicle>;
    unassignedCubicles: Array<ICubicle>;
    notificationCount: number;
    publicIp: string;
    privateIp: string;
    cubiclesLoading: boolean;
    defaultImgUrl: string = 'assets/images/broken.png';
    url: string;
    loadingSettings: boolean;
    isTheme: boolean;
    themeColor: any;

    providerId: number;
    providersInput = new Subject<string>();
    providers: Observable<Array<IResource>>;
    loadingProviders: boolean;
    isAssigningDoctor: boolean;
    currentAssignedCubicles: Array<ICubicle>;
    currentUnAssignedCubicles: Array<ICubicle>;
    unAssignedCubiclespagination: Pagination;
    assignedCubiclespagination: Pagination;
    unAssignedCubiclespaginationFlag: boolean = true;
    sideSubMenu: any = document.getElementsByClassName("sidebar-main-menu");
    constructor(
        private readonly identityService: IdentityService,
        private readonly appData: AppData,
        private readonly router: Router,
        private readonly modalService: NgbModal,
        private readonly notifyService: NotifyService,
        private readonly resourceService: ResourceService,
        private readonly httpService: HttpService,
        private readonly menuService: MenuService,
        private readonly formBuilder: FormBuilder,
        public httpErrorService: HttpErrorService,
        public settingService: SettingService,
        public communicationService: CommunicationService,
        public readonly jitsiService: JitsiService,

        //private sanitizer: DomSanitizer
    ) {
        this.setUpMenu();
        this.page = new Page();
        this.auditlog = new AuditLog();
        this.settings = new Settings();//
        this.logoBasics = new Setting();
        this.assignedCubicles = new Array<ICubicle>();
        this.unassignedCubicles = new Array<ICubicle>();
        this.communicationService.createConnection(() => {
            this.communicationService.startConnection("QueueManagement");
        });
        this.unAssignedCubiclesinitPagination();
        this.assignedCubiclesinitPagination();

    }
    private unAssignedCubiclesinitPagination() {
        this.unAssignedCubiclespagination = new Pagination();
        this.unAssignedCubiclespagination.pageIndex = 1;
        this.unAssignedCubiclespagination.pageSize = 10;
    }
    private assignedCubiclesinitPagination() {
        this.assignedCubiclespagination = new Pagination();
        this.assignedCubiclespagination.pageIndex = 1;
        this.assignedCubiclespagination.pageSize = 10;
    }

    safe = (url: any) => {
        if (url) {
            return `${ApiResources.getURI(ApiResources.resources.base, ApiResources.resources.getProfileImage)}?imagePath=${url}`;
        }
        return this.defaultImgUrl;
    }

    private onFetchPublicIp() {
        fetch('https://jsonip.com', { mode: 'cors' })
            .then((resp) => resp.json())
            .then((ip) => {
                this.publicIp = ip.ip;
                this.jitsiService.ipAddress = ip.ip;
            });
    }

    private onReadPrivateIp() {
        // this.privateIp = document.getElementById("ip").innerHTML;
    }

    onNotificationToggle() {
        if (!this.showTicket) {
            this.showTicket = true;
            this.fetchNotifications();
        } else {
            this.showTicket = false;
        }

    }

    onNavigate(item: Notification) {
        this.showTicket = false;
        if (UtilHelper.isEmpty(item.redirectionLink) && UtilHelper.isEmpty(item.referenceId)) {
            this.router.navigateByUrl(`${item.redirectionLink}/${item.encryptedReferenceId}`);
        }
    }

    setUpMenu = () => {
        this.defaultMenu = this.menuService.getDefaultRoute;
        this.menus = this.menuService.menus(MenuType.MainMenu);
        this.allMenus = this.menuService.menus().filter(x => x.mainPage);
        this.allMenus = this.menuService.menus().filter(x => (x.url || '').toLowerCase().indexOf(':id'.toLowerCase()) === -1 && x.mainPage !== null && (x.menuTypeId !== 4))
        this.allMenuAndSubMenu = this.menuService.menus();
        this.menuHolder = new MenuHolder();
        this.menuHolder.subMenus = new Array<IMenuModel>();
        this.setMenuMarkers();
    }

    @HostListener("window:scroll", ["$event"])
    onScroll(event) {
        const $toTop = $(".btn-scroll-top");
        if ($(event.currentTarget).scrollTop() !== 0) {
            $toTop.fadeIn();
        } else {
            $toTop.fadeOut();
        }
    }

    scrollToTop() {
        $("body,html").animate(({ scrollTop: 0 }) as any, 500);
    }

    onToggleMenu(event: Event) {
        event.preventDefault();

        const sidebarSize = $("body").attr("data-sidebar-size");
        if ($("window").width() >= 993) {
            if (sidebarSize === "condensed") {
                //self.changeSize(defaultSidebarSize);
            }
            //else {
            //    //self.changeSize('condensed');
            //}
        } else {
            //self.changeSize(defaultSidebarSize);
            $("body").toggleClass("sidebar-enable");
        }
    }

    sos() {
        var t = document.getElementsByTagName("body")[0];
        if (t.classList) {
            t.classList.remove("sidebar-enable");
        }
    }
    dontLeave() {
        var newidebarSize = document.getElementsByTagName("body")[0];
        if ($("window").width() >= 993) {

        } else {
            //self.changeSize(defaultSidebarSize);
            newidebarSize.classList.add("sidebar-enable");
        }
    }

    formatMatches = (item: IResource) => item.value || "";

    formatMenuMatches = (item: IMenuModel) => item.displayName || "";

    search = (text$: Observable<string>) =>
        text$.pipe(
            debounceTime(100),
            distinctUntilChanged(),
            tap(() => this.searching = true),
            switchMap((term: string) =>
                term.length < 2 ? of([]) : this.resourceService
                    .patients(term)
                    .pipe(
                        tap(() => this.searchFailed = false),
                        catchError(() => {
                            this.searchFailed = true;
                            return of([]);
                        })
                    )
            ),
            tap(() => this.searching = false)
        );

    menuSearch = (text$: Observable<string>) =>
        text$.pipe(
            distinctUntilChanged(),
            tap(() => this.searching = true),
            switchMap((term: string) => {
                return of((this.allMenus.filter(x => (x.mainPage || '').toLowerCase().indexOf(term.toLowerCase()) !== -1 ||
                    (x.subPage || '').toLowerCase().indexOf(term.toLowerCase()) !== -1 || (x.displayName || '').toLowerCase().indexOf(term.toLowerCase()) !== -1)) || []);

            }),
            tap(() => this.searching = false)
        );

    onSelectPatient(event: NgbTypeaheadSelectItemEvent) {
        if (event.item && (event.item as IResource).encryptedId) {
            this.router.navigate([]).then(() => { location.assign(`${location.pathname}#/app/patient/${event.item.encryptedId}`); });
        } else {
            event.preventDefault();
        }
    }

    onSelectMenu(event: NgbTypeaheadSelectItemEvent) {
        if (event.item && (event.item as IMenuModel).url) {
            this.router.navigate([event.item.url]);
        } else {
            event.preventDefault();
        }
    }
    private buildUserForm() {
        this.userForm = this.formBuilder.group({
            userId: 0,
            firstName: [null, [Validators.required]],
            lastName: [null, [Validators.required]],
            middleName: [null],
            gender: [null],
            roleId: [null, [Validators.required]],
            dateOfBirth: [null],
            email: [null, [Validators.required]],
            mobile: [null, [Validators.required]],
            countryName: [null, [Validators.required]],
            base64ProfileImage: [null],
            profileImageUrl: [null],
            providerLocationId: [{ value: null, disabled: true }, [Validators.required]],
            provider: [{ value: null, disabled: true }, [Validators.required]]
        });
    }

    private updateForm() {
        this.userForm.patchValue({
            userId: this.user.userId,
            firstName: this.user.firstName,
            lastName: this.user.lastName,
            middleName: this.user.middleName,
            email: this.user.email,
            mobile: this.user.mobile,
            countryName: this.user.countryName,
            roleId: this.user.roleId,
            providerLocationId: this.user.providerLocationId,
            gender: this.user.gender,
            dateOfBirth: this.user.dateOfBirth,
            profileImageUrl: this.user.profileImageUrl
        });
    }

    get profileForm() { return this.userForm.controls; }

    onProfile() {
        if (this.page.userAccount.roleId === Role.Provider) {
            this.router.navigateByUrl(`app/providers/${this.page.userAccount.encryptedReferenceId}`);
        } else {
            this.buildUserForm();
            this.fetchUsersProfile();
            this.modalRef = this.modalService.open(this.templateModify, {
                backdrop: "static",
                keyboard: false,
                centered: true,
                size: "lg",
                windowClass: "custom-modal effect-scale"
            });
        }
    }

    private fetchUsersProfile() {
        this.userLoading = true;
        const request = {
            encryptedUserId: this.page.userAccount.encryptedReferenceId
        };
        this.httpService.post(ApiResources.getURI(ApiResources.users.base, ApiResources.users.find), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => {
                this.userLoading = false;
            }))
            .subscribe((response: IUser) => {
                this.user = response;
                this.updateForm();
            }, () => {
                this.user = null;
                this.onCloseModal();
                this.notifyService.error("Error Occurred while getting your Profile.");
            });
    }

    onProfileSubmit() {
        this.submitted = true;
        if (!this.userForm.valid) {
            return;
        }

        this.submitting = true;
        const request = Object.assign(UtilHelper.clone(this.userForm.getRawValue()));
        request.modifiedBy = this.page.userAccount.accountId;
        this.httpService.put(ApiResources.getURI(ApiResources.users.base, ApiResources.users.update), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => {
                this.submitting = false;
                this.submitted = false;
                this.onCloseModal();
            }))
            .subscribe((response: string) => {
                this.notifyService.success(response);
            },
                () => {
                    this.notifyService.error("Error occurred while updating profile.");
                });
    }

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

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

        this.submitted = undefined;
        this.submitting = undefined;
        this.unAssignedCubiclespaginationFlag = true;
    }

    onShowSettings() {
        $("body").addClass("right-bar-enabled");
    }

    onCloseSettings() {
        $("body").removeClass("right-bar-enabled");
    }

    onApplySettings() {
        this.httpService.post(ApiResources.getURI(ApiResources.providers.base, ApiResources.providers.modifySettings), this.settings)
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe(
                (response: Settings) => {
                    this.settings = response;
                    $("body").removeClass("right-bar-enabled");
                },
                () => {
                    this.notifyService.defaultError();
                }
            );
    }

    onCancelSettings() {
        $("body").removeClass("right-bar-enabled");
    }

    onSubmit() {
        this.submitted = true;
        if (!this.changePasswordForm.valid || (this.changePasswordForm.controls.password.errors || this.changePasswordForm.controls.confirmPassword.errors)) {
            return;
        }

        this.submitting = true;
        this.httpService
            .put<string>(ApiResources.getURI(ApiResources.account.base, ApiResources.account.updatePassword), this.changePasswordForm.value)
            .pipe(
                finalize(() => {
                    this.submitted = false;
                    this.submitting = false;
                })
            )
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe(
                (message: string) => {
                    this.notifyService.success(message);
                    this.onCloseModal();
                    this.onLogout();
                },
                () => {
                    this.notifyService.defaultError();
                }
            );
    }

    private buildForm() {
        this.changePasswordForm = this.formBuilder.group({
            accountId: [this.page.userAccount.accountId],
            password: ["", [Validators.required, Validators.minLength(4)]],
            confirmPassword: ["", [Validators.required, Validators.minLength(4)]],
            locationId: this.page.userAccount.locationId
        }, { validator: CompareValidator.compare("password", "confirmPassword") });
    }

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

    onLogout(isHardReload: boolean = false) {
        this.auditlog.AccountId = this.page.userAccount.accountId;
        this.auditlog.roleName = this.page.userAccount.roleName;
        this.auditlog.fullName = this.page.userAccount.fullName;
        this.auditlog.logDescription = "<b>" + this.page.userAccount.fullName + "</b>" + "(" + this.page.userAccount.roleName + ")" + " has been logout.";
        this.auditlog.logTypeName = "Account";
        this.auditlog.logTypeId = 8;
        this.auditlog.logFrom = this.page.userAccount.roleId;

        try {
            this.communicationService.stopConnection();
        } catch (e) {
            console.log(e);
        }

        this.identityService.signOut()
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe(() => {
                this.auditlogService(this.auditlog);
                //LocalStorageHelper.DeleteAll();
                this.appData.setAccount(null);
                delete localStorage["ProviderVideoCallingSession"];
                this.menuService.removeFromLocal();
                if (isHardReload) {
                    this.router.navigateByUrl(appUrls.login).then(() => {
                        location.reload();
                    });
                } else {
                    this.router.navigateByUrl(appUrls.login);
                }
            });
    }

    auditlogService(request: AuditLog) {
        this.httpService.post(ApiResources.getURI(ApiResources.auditlog.base, ApiResources.auditlog.insert), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((response) => {
                console.log(response);
            }, () => {
            });
    }


    getWebVersion() {
        this.httpService
            .get(ApiResources.getURI(ApiResources.application.base, ApiResources.application.version))
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe(
                (response: any) => {
                    this.webVersion = response["version"];
                },
                () => {
                }
            );
    }

    ngOnInit() {

        this.logoSubscription = this.settingService.get.subscribe((value: boolean) => {
            if (value) {
                this.getLogoImage();
            }
        });

        this.appData.userAccount
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((userAccount: IUserAccount) => {

                if (!userAccount)
                    return;
                this.page.userAccount = userAccount ? userAccount : undefined;
                this.onFetchPublicIp();
                this.fetchProviders();
                // this.onReadPrivateIp();
                this.getLogoImage();
                this.getSettingsLayoutCommon();
                if (this.menuService.isHitMenu) {
                    this.menuService.fetch(this.page.userAccount.accountId, this.page.userAccount.roleId, () => {
                        this.setUpMenu();
                    });
                }
                this.getWebVersion();
                this.onAssignConsultantDoctor({
                    accountId: this.page.userAccount.accountId,
                    providerId: this.page.userAccount.roleId == 3 ? this.page.userAccount.referenceId : undefined
                } as ICubicle, () => {
                    this.fetchCubicles(true);
                })
                // this.requestPermission();
            });
        this.router.events.pipe(takeUntil(this.page.unSubscribe)).subscribe(event => {
            if (event instanceof NavigationEnd) {
                this.activeRoute = event.url;
            }
        });

        // let interval = setInterval(() => {
        //     let appConfigUrl = { ...AppConfig.settings };
        //     if (UtilHelper.isEmpty(appConfigUrl["hostingUrl"])) {
        //         this.url = appConfigUrl["hostingUrl"];
        //         clearInterval(interval);
        //     }
        // }, 10);
    }

    onProviderChange(event: any) {
        if (event) {
            this.onAssignConsultantDoctor({
                accountId: this.page.userAccount.accountId,
                providerId: event.id
            } as ICubicle)
        }
    }

    private fetchProviders() {
        this.providers = this.providersInput.pipe(
            debounceTime(500),
            distinctUntilChanged(),
            switchMap((term: string) =>
                term && term.length >= 2
                    ? this.resourceService.consultatDoctors(term).pipe(
                        tap(() => this.loadingProviders = true),
                        catchError(() => { return of([]) }),
                        finalize(() => this.loadingProviders = false)
                    )
                    : of([])
            )
        );
    }

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

    fetchCubicles = (isBypass: boolean = false) => {
        if (!isBypass) {
            this.openCubicleModal();
        }

        setTimeout(() => {
            this.cubiclesLoading = true
            const request = {
                pageIndex: 1,
                pageSize: 100,
                locationId: this.page.userAccount.locationId
            };
            this.httpService.post(ApiResources.getURI(ApiResources.cubicles.base, ApiResources.cubicles.fetch), request)
                .pipe(takeUntil(this.page.unSubscribe))
                .pipe(finalize(() => this.cubiclesLoading = false))
                .subscribe(
                    (response: GenericResponse) => {
                        if (response.status === GenericStatus[GenericStatus.Success]) {
                            this.refineCubicles(response.data);
                        }
                    },
                );
        })
    }

    refineCubicles = (cubiclesData: any) => {
        const records = (cubiclesData as Array<ICubicle>).map(x => ({ ...x, providerName: x.providerName ? x.providerName.toLowerCase() : null }));
        this.assignedCubicles = records.filter(x => x.providerId);
        this.currentAssignedCubicles = records.filter(x => x.providerId).slice(0, CUBICLE_PAGE_SIZE);
        if (this.currentAssignedCubicles.length > 0) {
            UtilHelper.applyPagination(this.currentAssignedCubicles, this.assignedCubiclespagination);
        }
        this.unassignedCubicles = records.filter(x => !x.providerId);
        this.currentUnAssignedCubicles = records.filter(x => !x.providerId).slice(0, CUBICLE_PAGE_SIZE);
        if (this.currentUnAssignedCubicles.length > 0) {
            UtilHelper.applyPagination(this.currentUnAssignedCubicles, this.unAssignedCubiclespagination);
        }
        this.settingService.cubicles = this.assignedCubicles.filter(x => x.accountId == this.page.userAccount.accountId);
    }
    onAssignedPageChange = (index: number) => {
        const startIndex = index * CUBICLE_PAGE_SIZE;
        this.currentAssignedCubicles = LinqHelper.cloneDeepArray(this.assignedCubicles.slice(startIndex, startIndex + CUBICLE_PAGE_SIZE));
    }
    onUnAssignedPageChange = (index: number) => {
        const startIndex = index * CUBICLE_PAGE_SIZE;
        this.currentUnAssignedCubicles = LinqHelper.cloneDeepArray(this.unassignedCubicles.slice(startIndex, startIndex + CUBICLE_PAGE_SIZE))
    }
    onUnAssignedCubicleSearch = (id: any) => {
        if (id) {
            this.unAssignedCubiclespaginationFlag = false;
            this.currentUnAssignedCubicles = LinqHelper.cloneDeepArray(this.unassignedCubicles.filter(x => x.cubicleId === id.cubicleId));
        }
        if (id === undefined) {
            this.unAssignedCubiclespaginationFlag = true;
            this.currentUnAssignedCubicles = this.unassignedCubicles.filter(x => !x.providerId).slice(0, CUBICLE_PAGE_SIZE);
        }
    }

    onAssignConsultantDoctor = (item: ICubicle, callback?: Function) => {
        this.isAssigningDoctor = true;
        const request = {
            accountId: item.accountId,
            providerId: item.providerId
        }
        this.httpService.post(ApiResources.getURI(ApiResources.cubicles.base, ApiResources.cubicles.assignConsultantDoctor), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe(
                (response: GenericResponse) => {
                    this.isAssigningDoctor = false;
                    if (response.status === GenericStatus[GenericStatus.Success]) {
                        this.settingService.selectedConsultantDoctor = response.data;
                        if (this.settingService.selectedConsultantDoctor && this.settingService.selectedConsultantDoctor.value) {
                            this.settingService.selectedConsultantDoctor.value = this.settingService.selectedConsultantDoctor.value.toLowerCase();
                        }
                        if (callback) {
                            callback();
                        }
                    }
                },
            );
    }

    clearConsultantDoctor = (component: NgSelectComponent) => {
        this.isAssigningDoctor = true;
        const request = {
            accountId: this.page.userAccount.accountId
        }
        this.httpService.post(ApiResources.getURI(ApiResources.cubicles.base, ApiResources.cubicles.unassignConsultantDoctor), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe(
                (response: GenericResponse) => {
                    this.isAssigningDoctor = false;
                    if (response.status === GenericStatus[GenericStatus.Success]) {
                        component && component.clearModel();
                        this.settingService.selectedConsultantDoctor = null;
                    }
                },
            );
    }

    onAssign = (item: ICubicle) => {
        if (item.loading) return;
        if (!this.settingService.selectedConsultantDoctor && this.page.userAccount.roleId !== 3) {
            this.notifyService.warning("Please select Consultant doctor.");
            return;
        }

        if (this.settingService.cubicles.length) {
            this.notifyService.warning("Only 1 room can be assigned");
            return;
        }

        item.loading = true;
        const request = {
            cubicleId: item.cubicleId,
            accountId: this.page.userAccount.accountId,
        }
        this.httpService.post(ApiResources.getURI(ApiResources.cubicles.base, ApiResources.cubicles.assign), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe(
                (response: GenericResponse) => {
                    item.loading = false;
                    if (response.status === GenericStatus[GenericStatus.Success]) {
                        item.providerId = this.settingService.selectedConsultantDoctor.id;
                        item.accountId = this.page.userAccount.accountId;
                        item.assignedName = this.page.userAccount.fullName.toLowerCase();
                        item.providerName = this.settingService.selectedConsultantDoctor.value.toLowerCase();
                        this.refineCubicles([...this.assignedCubicles, ...this.unassignedCubicles])
                    }

                    if (response.status === GenericStatus[GenericStatus.Info]) {
                        this.notifyService.warning("Please select consultant doctor");
                    }

                    if (response.status === GenericStatus[GenericStatus.Warning]) {
                        this.notifyService.warning("Room already assigned, Only 1 room can be assigned");
                    }
                },
            );
    }

    onUnassign = (item: ICubicle) => {
        if (item.loading) return;
        item.loading = true;
        const request = {
            cubicleId: item.cubicleId,
            providerId: null,
            accountId: item.accountId
        }
        this.httpService.post(ApiResources.getURI(ApiResources.cubicles.base, ApiResources.cubicles.unassign), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe(
                (response: GenericResponse) => {
                    item.loading = false;
                    if (response.status === GenericStatus[GenericStatus.Success]) {
                        item.providerId = null;
                        item.accountId = null;
                        item.assignedName = null;
                        this.refineCubicles([...this.assignedCubicles, ...this.unassignedCubicles])
                    }
                },
            );
    }

    fetchNotifications() {
        const request = {
            pageSize: 5,
            pageIndex: 1
        };
        this.loading = true;
        this.httpService.post<Array<Notification>>(ApiResources.getURI(ApiResources.webNotification.base, ApiResources.webNotification.fetch), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loading = false))
            .subscribe((response: Array<Notification>) => {
                //response.forEach(x => {
                //    x["newThumbnailUrl"] = x.patientThumbnailUrl ? this.safe(x.patientThumbnailUrl) : null;
                //})
                this.notifications = response;
                this.notificationCount = this.notifications.length > 0 ? this.notifications[0].totalItems : 0;
            }, () => {
                this.notifications = new Array<Notification>();
            });
    }

    getLogoImage = () => {
        this.loading = true;

        this.httpService
            .get<Array<Setting>>(ApiResources.getURI(ApiResources.setting.base, ApiResources.setting.fetch), { type: "Logo", active: true })

            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => { this.loading = false }))
            .subscribe(
                (response: Array<Setting>) => {
                    if (response && response.length > 0) {
                        this.logoBasics = response[0];
                        if (UtilHelper.isEmpty(response[0].imageUrl)) {
                            response[0].imageUrl = `${ApiResources.getURI(ApiResources.resources.base, ApiResources.resources.getProfileImage)}?imagePath=${response[0].imageUrl}`;
                        }
                    }

                },
                () => {
                    this.logoBasics = new Setting();
                }
            );
    }

    ngOnDestroy() {
        try {
            this.modalService.dismissAll();
        } catch (e) {
            // ignored;
        }
        this.showTicket = false;
        this.onCloseSettings();
        this.page.unSubscribe.next(null);
        this.page.unSubscribe.complete();
    }

    setMenuMarkers = () => {
        this.menus.forEach(m => {
            m.hasMarker = this.menuService.menus(MenuType.SubMenu, m.mainPage).length > 0;
        })
    }

    enter = (menu: IMenuModel) => {
        this.showTicket = false;
        this.menus.forEach(x => { x.isHovering = false; });
        if (menu.hasMarker) {
            menu.isHovering = true;
        }

        this.isHovering = true;
        this.menuHolder.menuName = menu.displayName + " Navigation";
        this.menuHolder.mainPage = menu.mainPage;
        this.menuHolder.menuUrl = menu.url;
        var allSubMenus = this.menuService.menus(MenuType.SubMenu, menu.mainPage);
        var onlySubMenus = allSubMenus.filter(x => x.menuTypeId === MenuType.SubMenu ||
            (x.menuTypeId === MenuType.CategoryMenu && x.category && x.category === x.displayName));
        onlySubMenus.filter(x => x.menuTypeId === MenuType.CategoryMenu).forEach(x => {
            x.categoryMenus = allSubMenus.filter(y => y.menuTypeId === MenuType.CategoryMenu && y.category === x.category && y.displayName !== x.displayName)
                .map((y, i) => ({
                    id: i,
                    subPage: y.subPage,
                    displayName: y.displayName,
                    iconClasses: y.iconClasses,
                    url: y.url,
                    priority: y.priority
                } as ICategoryMenuModel));
        });

        this.menuHolder.subMenus = onlySubMenus;
        setTimeout(() => {
            var v = document.getElementById("submenu");
            if (v && v.classList) {
                v.classList.add("d-block");
            }
        }, 100);
    }

    leaveMenu = () => {
        if (!this.menuHolder.subMenus.length) {
            this.isHovering = false;
            this.menus.forEach(x => { x.isHovering = false; });
        }
    }

    leave = () => {
        this.isHovering = false;
        this.menuHolder.subMenus = new Array<IMenuModel>();
        this.menus.forEach(x => { x.isHovering = false; });
    }
    private getSettingsLayoutCommon() {
        this.loadingSettings = true;
        this.httpService.get<Array<Setting>>(ApiResources.getURI(ApiResources.setting.base, ApiResources.setting.fetch), { name: "Theme Color" })
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loadingSettings = false))
            .subscribe((response: Array<Setting>) => {
                if (response.length > 0) {
                    this.isTheme = response[0].active;
                    this.themeColor = response[0].value;
                }
                this.onToggleTheme(this.themeColor);
            }, () => {
                this.onToggleTheme(this.themeColor);
            });
    }

    onToggleTheme(color: string) {
        switch (color) {
            case "#827d77 #fec32b #f5f6f9 #f86262":
                this.yellowTheme();
                break;
            default:
                this.blueTheme();
        }
    }
    //private getSettingsLayoutYellow() {
    //    debugger;
    //    this.loadingSettings = true;
    //    this.httpService.get<Array<Setting>>(ApiResources.getURI(ApiResources.setting.base, ApiResources.setting.fetch), { name: "Yellow Theme" })
    //        .pipe(takeUntil(this.page.unSubscribe))
    //        .pipe(finalize(() => this.loadingSettings = false))
    //        .subscribe((response: Array<Setting>) => {
    //            debugger;

    //            if (response.length > 0) {
    //                this.isYellowTheme = response[0].active;
    //                console.log("from yellow" + this.isYellowTheme);
    //                if (this.isYellowTheme) {
    //                    this.yellowTheme();
    //                }
    //            }

    //        });
    //}
    yellowTheme() {
        var head = document.getElementsByTagName('head')[0];
        var fileref = document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        var fileName = location.origin + location.pathname + "assets/css/yellow-theme.css";
        fileref.setAttribute("href", fileName);
        fileref.media = 'all';
        head.appendChild(fileref);
    }
    blueTheme() {
        var head = document.getElementsByTagName('head')[0];
        var fileref = document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        var fileName = location.origin + location.pathname + "assets/css/blue-theme.css";
        fileref.setAttribute("href", fileName);
        fileref.media = 'all';
        head.appendChild(fileref);
    }
    onToggleSubMenu(event: Event, threeDot: HTMLElement) {

        event.preventDefault();
        const sideSubMenu = document.getElementsByClassName("sidebar-main-menu")[0].classList;             

        if ($("window").width() >= 99) {


        } else {            
            if (threeDot.classList.contains("d-none")) {
                threeDot.classList.toggle("text-success");
            }
            threeDot.classList.toggle("text-danger");
            sideSubMenu.toggle("addedLeft");          

        }
    }

}