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

class TrackBy {
    role(item: DischargeInstructions) {
        return item.dischargeInstructionId;
    }
}

class FilterOptions {
    dischargeInstructionName: string = null;
    dischargeInstructionId: number;

}

class Filters {
    options: FilterOptions;
    applied: boolean;
    constructor() {
        this.init();
    }

    init() {
        this.options = new FilterOptions();
        this.applied = undefined;
    }
}

@Component({
    templateUrl: "./discharge-instructions.html",
    encapsulation: ViewEncapsulation.None
})
export class DischargeInstructionsPage implements OnInit, OnDestroy {
    page: Page;
    filters: Filters;
    trackBy: TrackBy;
    pagination: Pagination;
    loading: boolean;
    discharges: Array<DischargeInstructions>;
    selectedDischarges: DischargeInstructions;
    modalRef: NgbModalRef;
    dischargeForm: FormGroup;
    submitting: boolean;
    submitted: boolean;
    loadingDischarges: boolean;
    modifying: boolean;
    modifyingContent: string;    

    constructor(
        private readonly appData: AppData,
        private readonly modalService: NgbModal,
        private readonly formBuilder: FormBuilder,
        private readonly notifyService: NotifyService,
       private readonly httpService: HttpService
    ) {
        this.loading = true;
        this.page = new Page();
        this.filters = new Filters();
        this.trackBy = new TrackBy();
        this.loading = true;
        this.initPagination();
    }

    private initPagination() {
        this.pagination = new Pagination();
        this.pagination.pageIndex = 1;
        this.pagination.pageSize = 10;
    }

    private fetchDischargeInstuctions() {
        
        const request = Object.assign(UtilHelper.clone(this.filters.options), UtilHelper.clone(this.pagination));
        this.httpService.post<Array<DischargeInstructions>>(ApiResources.getURI(ApiResources.discharges.base, ApiResources.discharges.fetch), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loading = false))
            .subscribe((response: Array<DischargeInstructions>) => {
                this.discharges = response;
                UtilHelper.applyPagination(this.discharges, this.pagination);
            });
    }

    private buildForm() {
        this.dischargeForm = this.formBuilder.group({
            dischargeInstructionId: 0,
            dischargeInstructionName: [null, [Validators.required, WhiteSpaceValidator.isValid]],
            active: [ true ],
        });
    }

    private updateForm() {
        this.dischargeForm.patchValue({
            dischargeInstructionId: this.selectedDischarges.dischargeInstructionId,
            dischargeInstructionName: this.selectedDischarges.dischargeInstructionName,
            active: this.selectedDischarges.active
        });
    }

    onOpenModel(content: TemplateRef<any>, discharge?: DischargeInstructions) {
        
        this.buildForm();

        if (discharge) {
            this.selectedDischarges = discharge;
            this.updateForm();
        }

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

    onSubmit() {
        this.submitted = true;
        if (!this.dischargeForm.valid) {
            return;
        }
        console.log(this.dischargeForm.value);
        this.submitting = true;
        const request = Object.assign(UtilHelper.clone(this.dischargeForm.getRawValue()));
        request["modifiedByName"] = this.page.userAccount.fullName;
        request.modifiedBy = this.page.userAccount.accountId;
        if (Number(this.dischargeForm.value.dischargeInstructionId) === 0) {
            request.createdBy = this.page.userAccount.accountId;
            this.httpService.post(ApiResources.getURI(ApiResources.discharges.base, ApiResources.discharges.add), request)
                .pipe(takeUntil(this.page.unSubscribe))
                .pipe(finalize(() => {
                    this.submitting = false;
                    this.submitted = false;
                }))
                .subscribe(() => {
                    this.onCloseModal();
                    this.fetchDischargeInstuctions();
                    this.notifyService.success("Discharge instructions Added successfully.");
                }, (error: HttpErrorResponse) => {
                    const errorMessage = UtilHelper.handleError(error);
                    if (errorMessage) {
                        this.notifyService.warning(errorMessage);
                    } else {
                        this.notifyService.defaultError();
                    }
                });
        } else {
            request.modifiedBy = this.page.userAccount.accountId;
            request["modifiedByName"] = this.page.userAccount.fullName;
            request["createdBy"] = this.page.userAccount.accountId;
            delete request.type;
            this.httpService.put(ApiResources.getURI(ApiResources.discharges.base, ApiResources.discharges.update), request)
                .pipe(takeUntil(this.page.unSubscribe))
                .pipe(finalize(() => {
                    this.submitting = false;
                    this.submitted = false;
                }))
                .subscribe(() => {
                    this.onCloseModal();
                    this.fetchDischargeInstuctions();
                    this.notifyService.success("Discharge instructions details has been updated successfully.");
                }, (error: HttpErrorResponse) => {
                    const errorMessage = UtilHelper.handleError(error);
                    if (errorMessage) {
                        this.notifyService.warning(errorMessage);
                    } else {
                        this.notifyService.defaultError();
                    }
                });
        }
    }

    //onDelete(discharge: DischargeInstructions) {
    //    this.notifyService.delete(() => {
    //        this.httpService
    //            .post(ApiResources.getURI(ApiResources.discharges.base, ApiResources.discharges.delete), { dischargeInstructionId: discharge.dischargeInstructionId })
    //            .pipe(takeUntil(this.page.unSubscribe))
    //            .pipe(finalize(() => { }))
    //            .subscribe(
    //                () => {
    //                    this.notifyService.success("Discharge instructions deleted successfully.");
    //                    this.fetchDischargeInstuctions();
    //                }
    //            );
    //    }, () => { });
    //}

    onModifyStatus(item: DischargeInstructions, status: boolean) {
        this.notifyService.confirm(`You want to ${status ? 'Activate' : 'Deactivate'} this Discharge Instructions ?`, () => {
            const request = {
                modifiedBy: this.page.userAccount.accountId,
                active: status,
                dischargeInstructionId: item.dischargeInstructionId,
                modifiedByName: this.page.userAccount.fullName,
                createdByRole: this.page.userAccount.roleName,
                loginRoleId: this.page.userAccount.roleId,
                dischargeInstructionName: item.dischargeInstructionName
            };

            this.httpService.post(ApiResources.getURI(ApiResources.discharges.base, ApiResources.discharges.modifyStatus), request)
                .pipe(takeUntil(this.page.unSubscribe))
                .pipe(finalize(() => { this.loading = false }))
                .subscribe((response: number) => {
                    if (response > 0) {
                        this.notifyService.successToast(`${status ? 'Activated' : 'Deactivated'} successfully.`);
                    }
                    this.fetchDischargeInstuctions();
                }, (error: HttpErrorResponse) => {
                    this.notifyService.errorToast(error.error);
                });
        });
    }

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

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

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

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

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

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