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

class FilterOptions {
    payCategoryId: number = null;
    active?: boolean = null;
}

class Filters {
    options: FilterOptions;
    applied: boolean;

    constructor() {
        this.init();
    }

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

@Component({
    templateUrl: "./pay-categories.html",
    encapsulation: ViewEncapsulation.None
})
export class PayCategoryPage implements OnInit, OnDestroy {
    page: Page;
    pagination: Pagination;
    filters: Filters;
    loading: boolean;
    paycategories: Array<PayCategory>;

    payForm: FormGroup;
    selected: PayTypes
    modalRef: NgbModalRef;
    payCategoryNames: Array<IResource>;
    submitting: boolean;
    submitted: boolean;
    alreadyExists: boolean;


    constructor(
        private readonly appData: AppData,
        private readonly httpService: HttpService,
        private readonly notifyService: NotifyService,
        private readonly formBuilder: FormBuilder,
        private readonly modalService: NgbModal,
        private readonly resourceService: ResourceService

    ) {
        this.loading = true;
        this.page = new Page();
        this.filters = new Filters();
        this.initPagination();
    }

    private buildForm() {
        this.payForm = this.formBuilder.group({
            payCategoryId: 0,
            payCategoryName: [null, [Validators.required, Validators.minLength(2), WhiteSpaceValidator.isValid]],
        })
        this.payForm.get("payCategoryName").valueChanges.subscribe((value: string) => { if (value) { this.alreadyExists = false } });
    }

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

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

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

    private fetchpayCategoryNames() {
        this.resourceService.payCategories()
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((response: Array<IResource>) => {
                this.payCategoryNames = response;
            });
    }

    onSubmit() {
        this.submitted = true;
        if (this.payForm.invalid) {
            return;
        }
        this.submitting = true;
        const request = this.payForm.getRawValue()
        request["createdBy"] = this.page.userAccount.accountId
        request["modifiedBy"] = this.page.userAccount.accountId
        request["loginRoleId"] = this.page.userAccount.roleId
        request["createdByName"] = this.page.userAccount.fullName,
        request["modifiedByName"] = this.page.userAccount.fullName
        var url = ApiResources.getURI(ApiResources.payCategories.base, ApiResources.payCategories.insert);
        if (request["payCategoryId"] > 0) {
            url = ApiResources.getURI(ApiResources.payCategories.base, ApiResources.payCategories.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["payCategoryId"] > 0 ? 'updated' : 'added'} successfully.`);
                    }
                    this.onCloseModal();
                    this.fetchpayCategoryNames();
                    this.fetchPayCats();
                },
                (error: HttpErrorResponse) => {
                    if (error.status === 409) {
                        this.alreadyExists = true;
                    }
                    const errorMessage = UtilHelper.handleError(error);
                    if (errorMessage) {
                        this.notifyService.warning(errorMessage);
                    } else {
                        this.notifyService.defaultError();
                    }
                }
            );
    }

    onModifyStatus(item: PayCategory, status: boolean) {
        this.notifyService.confirm(`You want to ${status ? 'Activate' : 'Deactivate'} this Pay Category?`, () => {
            const request = {
                modifiedBy: this.page.userAccount.accountId,
                active: status,
                payCategoryId: item.payCategoryId,
                payCategoryName: item.payCategoryName,
                loginRoleId: this.page.userAccount.roleId,
                modifiedByName: this.page.userAccount.fullName
            };

            this.httpService.post(ApiResources.getURI(ApiResources.payCategories.base, ApiResources.payCategories.modifyPayTypeStatus), 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.fetchPayCats();
                }, (error: HttpErrorResponse) => {
                    this.notifyService.errorToast(error.error);
                });
        });
    }

    onOpenModel(content: TemplateRef<any>, item?: PayCategory) {
        this.buildForm();
        if (item) {
            this.payForm.patchValue({
                payCategoryId: item.payCategoryId,
                payCategoryName: item.payCategoryName,
            });
        }
        this.modalRef = this.modalService.open(content, {
            backdrop: "static",
            keyboard: false,
            centered: true,
            windowClass: "custom-modal effect-scale"
        });
    }

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

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

    onApplyFilters() {
        this.filters.applied = UtilHelper.isFiltersApplied(this.filters.options);
        this.initPagination();
        this.loading = true;
        this.fetchPayCats();
        this.onCloseFilters();
    }

    onResetFilters() {
        this.filters.init();
        this.loading = true;
        this.fetchPayCats();
        this.onCloseFilters();
    }

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

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

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