import { Component, OnDestroy, OnInit, ViewEncapsulation, TemplateRef } from "@angular/core";
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 { ConsultationType } from "@shared/entities/consultation-type.entity";

class TrackBy {
    consultationType(item: ConsultationType) {
        return item.consultationTypeId;
    }
}

class FilterOptions {
    name: string = null;
    consultationTypeId: number;
}

class Filters {
    options: FilterOptions;
    applied: boolean;

    constructor() {
        this.init();
    }

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

@Component({
    templateUrl: "./consultation-type.html",
    encapsulation: ViewEncapsulation.None
})
export class ConsultationTypePage implements OnInit, OnDestroy {
    page: Page;
    filters: Filters;
    trackBy: TrackBy;
    pagination: Pagination;
    consultationTypeForm: FormGroup;
    loading: boolean;
    consultationType: Array<ConsultationType>;
    selectedConsultationType: ConsultationType;

    modalRef: NgbModalRef;
    submitting: boolean;
    submitted: 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.initPagination();
    }

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

    private buildForm() {
        this.consultationTypeForm = this.formBuilder.group({
            consultationTypeId: 0,
            name: [null, [Validators.required]],
            active: [true],
        });
    }

    onOpenModel(content: TemplateRef<any>, consultationType?: ConsultationType) {

        this.buildForm();

        if (consultationType) {
            this.selectedConsultationType = consultationType;
            this.updateForm();
        }

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

    fetchAddConsultationTypes() {
        this.loading = true;

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

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

    onSubmit() {
        this.submitted = true;

        if (!this.consultationTypeForm.valid) {
            return;
        }
        console.log(this.consultationTypeForm.value);
        this.submitting = true;
        const request = Object.assign(UtilHelper.clone(this.consultationTypeForm.getRawValue()));
        request["modifiedByName"] = this.page.userAccount.fullName;
        request.createdBy = this.page.userAccount.accountId;
            this.httpService.post(ApiResources.getURI(ApiResources.consultationType.base, ApiResources.consultationType.add), request)
                .pipe(takeUntil(this.page.unSubscribe))
                .pipe(finalize(() => {
                    this.submitting = false;
                    this.submitted = false;
                }))
                .subscribe(() => {
                    this.onCloseModal();
                    this.fetchAddConsultationTypes();
                    if (Number(this.consultationTypeForm.value.consultationTypeId) === 0) {
                        this.notifyService.success("Consultation Type has been added successfully.");
                    } else {
                        this.notifyService.success("Consultaion Type details has been updated successfully.");
                    }
                }, (error: HttpErrorResponse) => {
                    const errorMessage = UtilHelper.handleError(error);
                    if (errorMessage) {
                        this.notifyService.warning(errorMessage);
                    } else {
                        this.notifyService.defaultError();
                    }
                });
         
    }

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

    private updateForm() {
        this.consultationTypeForm.patchValue({
            consultationTypeId: this.selectedConsultationType.consultationTypeId,
            name: this.selectedConsultationType.name,
            active: this.selectedConsultationType.active
        });
    }

    onDelete(consultationType: ConsultationType) {

        this.notifyService.delete(() => {
            this.httpService
                .post(ApiResources.getURI(ApiResources.consultationType.base, ApiResources.consultationType.delete), {
                    consultationTypeId: consultationType.consultationTypeId, modifiedByName: this.page.userAccount.fullName,
                    createdBy: this.page.userAccount.accountId,
                    modifiedBy: this.page.userAccount.accountId
                })
                .pipe(takeUntil(this.page.unSubscribe))
                .subscribe(
                    () => {
                        this.notifyService.success("Consultation Type deleted successfully.");
                        this.fetchAddConsultationTypes();
                    }, (error: HttpErrorResponse) => {
                        const errorMessage = UtilHelper.handleError(error);
                        if (errorMessage) {
                            this.notifyService.warning(errorMessage);
                        } else {
                            this.notifyService.defaultError();
                        }
                    }
                );
        }, () => {
            this.notifyService.defaultError();
        });
    }

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

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

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

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