import { Component, OnDestroy, OnInit, ViewEncapsulation } from "@angular/core";
import { ActivatedRoute, Router, RouterEvent, NavigationEnd, Params } from "@angular/router";
import { Page, IMenuModel } from "@shared/models";
import { takeUntil } from "rxjs/operators";

import { IAdmissionModel } from "./models/admission.model";
import { GenericResponse } from "@shared/models";
import { HttpService, FinalBillService, MenuService } from "@shared/services";
import { ApiResources } from "../../../shared/helpers";
import { FinalBillBasicModel } from "./models/final-bill-basic.model";
import { Subscription } from "rxjs";
import { MenuType } from "../../../shared/enums";
import { AdmissionFetchHelper } from "../progress-report/shared/helper";

@Component({
    templateUrl: "./services.html",
    styleUrls: ['./services.css'],
    encapsulation: ViewEncapsulation.None
})
export class ServicesPage implements OnInit, OnDestroy {
    page: Page;
    activeRoute: string;
    admissionId: string;
    loading: boolean;
    record: IAdmissionModel;

    finalBillBasics: FinalBillBasicModel;
    finalBillServiceSubscription: Subscription;

    isAdmission: boolean;
    menus: Array<IMenuModel>;

    constructor(
        private readonly router: Router,
        private readonly route: ActivatedRoute,
        private readonly httpService: HttpService,
        private readonly finalBillService: FinalBillService,
        private readonly admissionFetchHelper: AdmissionFetchHelper,
        private readonly menuService: MenuService
    ) {
        this.menus = this.menuService.menus(MenuType.SubMenu, "Services & Payments");
        this.finalBillBasics = new FinalBillBasicModel();
        this.page = new Page();
    }

    ngOnInit() {

        this.finalBillServiceSubscription = this.finalBillService.get.subscribe((value: boolean) => {
            if (value) {
                this.getFinalBillBasics();
            }
        });

        this.route.params
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((params: Params) => {
                this.admissionId = params["id"];
                this.isAdmission = params["type"] === "a";

                if (!this.isAdmission) {
                    this.menus = this.menus.filter(x => x.subPage !== 'discharge' && x.subPage !== 'gate-pass');
                }

                if (!this.isAdmission) {
                    this.menus = this.menus.filter(x => x.subPage !== 'discharge-patient');
                }

                if (!this.isAdmission) {
                    this.menus = this.menus.filter(x => x.subPage !== 'provisional-gate-pass');
                }

                const url = this.router.url;
                this.activeRoute = url.split("/")[url.split("/").length - 1];

                this.fetch();
                this.getFinalBillBasics();
            });

        this.router.events
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((event: RouterEvent) => {
                if (event instanceof NavigationEnd) {
                    const url = this.router.url;
                    this.activeRoute = url.split("/")[url.split("/").length - 1];
                }
            });
    }

    onViewDoctorProfile(encryptedProviderId: string) {
        this.router.navigateByUrl(`app/provider/${encryptedProviderId}`);
    }

    getFinalBillBasics = () => {
        this.httpService
            .post<GenericResponse>(ApiResources.getURI(ApiResources.finalBill.base, ApiResources.finalBill.getBasics), { id: this.admissionId, isAdmission: this.isAdmission })
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe(
                (response: GenericResponse) => {
                    this.finalBillBasics = response.data as FinalBillBasicModel;
                },
                () => {
                    this.finalBillBasics = new FinalBillBasicModel();
                }
            );
    }

    fetch = () => {
        this.admissionFetchHelper.admissionFetch(+this.admissionId, this.isAdmission, (data: IAdmissionModel) => {
            this.loading = false
            this.record = data;

            if (!this.isAdmission && this.record && this.record.status && this.record.status === "C") {
                this.menus = this.menus.filter(x => x.subPage !== 'orders');

                var url = this.router.url;
                url = url.replace(url.split("/")[url.split("/").length - 1], this.menus[this.menus.length - 1].subPage);
                this.activeRoute = url.split("/")[url.split("/").length - 1];

                this.router.navigateByUrl(url);
            }
        });
    }



    ngOnDestroy() {
        this.finalBillServiceSubscription.unsubscribe();
        this.page.unSubscribe.next();
        this.page.unSubscribe.complete();
    }
}