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 { ChargeTypes } from "@shared/entities/charge-types.entity";
import { WhiteSpaceValidator } from "../../../../../shared/validators";

class TrackBy {
    chargeTypes(item: ChargeTypes) {
        return item.chargeTypesId;
    }
}

class FilterOptions {
    chargeName: string = null;
    chargeTypesId: number;
}

class Filters {
    options: FilterOptions;
    applied: boolean;

    constructor() {
        this.init();
    }

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

@Component({
    templateUrl: "./charge-types.html",
    encapsulation: ViewEncapsulation.None
})
export class ChargeTypesPage implements OnInit, OnDestroy {
    page: Page;
    filters: Filters;
    trackBy: TrackBy;
    pagination: Pagination;
    chargeTypesForm: FormGroup;
    loading: boolean;
    chargeTypes: Array<ChargeTypes>;
    selectedChargeTypes: ChargeTypes;

    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.chargeTypesForm = this.formBuilder.group({
            chargeTypesId: 0,
            chargeName: [null, [Validators.required, WhiteSpaceValidator.isValid]],
            active: [true],
        });
    }  

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

        if (chargeTypes) {
            this.selectedChargeTypes = chargeTypes;
            this.updateForm();
        }

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

    fetchAddChargeTypes() {
        this.loading = true;

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

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

    onSubmit() {
        
        this.submitted = true;

        if (!this.chargeTypesForm.valid) {
            return;
        }
        console.log(this.chargeTypesForm.value);
        this.submitting = true;
        const request = Object.assign(UtilHelper.clone(this.chargeTypesForm.getRawValue()));
        request["modifiedByName"] = this.page.userAccount.fullName;
        if (Number (this.chargeTypesForm.value.chargeTypesId) === 0) {
            request.createdBy = this.page.userAccount.accountId;
            this.httpService.post(ApiResources.getURI(ApiResources.chargeTypes.base, ApiResources.chargeTypes.add), request)
                .pipe(takeUntil(this.page.unSubscribe))
                .pipe(finalize(() => {
                    this.submitting = false;
                    this.submitted = false;
                }))
                .subscribe(() => {
                    this.onCloseModal();
                    this.fetchAddChargeTypes();
                    this.notifyService.success("Charge Type has been 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.chargeTypes.base, ApiResources.chargeTypes.update), request)
                .pipe(takeUntil(this.page.unSubscribe))
                .pipe(finalize(() => {
                    this.submitting = false;
                    this.submitted = false;
                }))
                .subscribe(() => {
                    this.onCloseModal();
                    this.fetchAddChargeTypes();
                    this.notifyService.success("Charge 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.chargeTypesForm.controls;
    }    

    private updateForm() {
        this.chargeTypesForm.patchValue({
            chargeTypesId: this.selectedChargeTypes.chargeTypesId,
            chargeName: this.selectedChargeTypes.chargeName,
            active: this.selectedChargeTypes.active
        });
    }  

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

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

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


    onModifyStatus(item: ChargeTypes, status: boolean) {

        this.notifyService.confirm(`You want to ${status ? 'Activate' : 'Deactivate'} this Charge Type?`, () => {
            const request = {
                createdBy: this.page.userAccount.accountId,
                active: status,
                chargeTypesId: item.chargeTypesId,
                createdByName: this.page.userAccount.fullName,
                createdByRole: this.page.userAccount.roleName,
                loginRoleId: this.page.userAccount.roleId,
                chargeName: item.chargeName
            };

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

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

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