import { Component, OnDestroy, OnInit, ViewEncapsulation, TemplateRef } from "@angular/core";
import { PayTypes } 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 { FormBuilder, Validators, FormGroup, FormControl } from "@angular/forms";
import { NgbModal, NgbModalRef } from "@ng-bootstrap/ng-bootstrap";
import { WhiteSpaceValidator } from "../../../../../shared/validators";

class FilterOptions {
    payTypeId: number = null;
    payTypeName: string = null;
    payTypeValue: string = null;
    salucroPayType: boolean = null;
    isActive: boolean = null;
}

class Filters {
    options: FilterOptions;
    applied: boolean;

    constructor() {
        this.init();
    }

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

@Component({
    templateUrl: "./pay-type.html",
    encapsulation: ViewEncapsulation.None
})
export class PayTypePage implements OnInit, OnDestroy {
    page: Page;
    pagination: Pagination;
    loading: boolean;
    paytypes: Array<PayTypes>;
    dropdownPaytypes: Array<IResource>;
    payTypeForm: FormGroup;
    selected: PayTypes
    modalRef: NgbModalRef;
    filters: Filters;
    submitting: boolean;
    submitted: boolean;
    salucroPayType: 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 initPagination() {
        this.pagination = new Pagination();
        this.pagination.pageIndex = 1;
        this.pagination.pageSize = 10;
    }

    private buildForm() {
        this.payTypeForm = this.formBuilder.group({
            payTypeId: new FormControl(null),
            payTypeName: [null, [Validators.required, WhiteSpaceValidator.isValid]],
            payTypeValue: [null],
            salucroPayType: new FormControl(false)
            

        })
    }

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

    private fetchPayTypes() {
        this.loading = true;
        const request = {
            ...this.pagination,
            ...this.filters.options
        };
        console.log(request);
        this.httpService.post(ApiResources.getURI(ApiResources.payTypes.base, ApiResources.payTypes.fetch),request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loading = false))
            .subscribe((response: Array<PayTypes>) => {
                this.paytypes = response;
                UtilHelper.applyPagination(this.paytypes, this.pagination);
            });
    }

    private filterPayTypes() {
        this.resourceService.allPayTypes(false)
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((response: Array<IResource>) => {
                this.dropdownPaytypes = response;
            });
    }

    onSubmit() {
        //debugger;
        
          
        this.submitted = true;
        if (this.payTypeForm.invalid) {
            return;
        }
        this.submitting = true;
        
         const request = {
             ...this.payTypeForm.getRawValue(),
            createdBy: this.page.userAccount.accountId,
            loginRoleId: this.page.userAccount.roleId,
            createdByName: this.page.userAccount.fullName,
             modifiedBy: this.page.userAccount.accountId,
             modifiedByName: this.page.userAccount.fullName,
        };

       // alert(JSON.stringify(this.payTypeForm.value))
        //alert(JSON.stringify(request))
            
        var url = ApiResources.getURI(ApiResources.payTypes.base, ApiResources.payTypes.insert);
        if (request["payTypeId"] > 0) {
            url = ApiResources.getURI(ApiResources.payTypes.base, ApiResources.payTypes.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["payTypeId"] > 0 ? 'updated' : 'added'} successfully.`);
                    }
                    if (response === -1) {
                        this.notifyService.warningToast("This Pay Type Name already exists.");
                        return;
                    }
                    this.onCloseModal();
                    this.filterPayTypes();
                    this.fetchPayTypes();
                },
                (error: HttpErrorResponse) => {
                    const errorMessage = UtilHelper.handleError(error);
                    if (errorMessage) {
                        this.notifyService.warningToast(errorMessage);
                    } else {
                        this.notifyService.defaultErrorToast();
                    }
                }
            );
    }
  
    onModifyStatus(item: PayTypes, status: boolean) {
        this.notifyService.confirm(`You want to ${status ? 'Activate' : 'Deactivate'} this pay type?`, () => {
            const request = {
                createdBy: this.page.userAccount.accountId,
                loginRoleId: this.page.userAccount.roleId,
                createdByName: this.page.userAccount.fullName,
                modifiedBy: this.page.userAccount.accountId,
                modifiedByName: this.page.userAccount.fullName,
                isActive: status,
                payTypeId: item.payTypeId,               
                payTypeName: item.payTypeName,
                payTypeValue: item.payTypeValue,
                salucroPayType: item.salucroPayType
                
                
            };

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

    onOpenModel(content: TemplateRef<any>, item?: PayTypes) {
        this.buildForm();
        if (item) {
            this.payTypeForm.patchValue({
                payTypeId: item.payTypeId,
                payTypeName: item.payTypeName,
                payTypeValue: item.payTypeValue,
                salucroPayType: item.salucroPayType
                
            });
            this.payTypeForm.get("payTypeValue").disable();
        }
        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;
        }
    }
    //public onSalicroChanged(value: boolean) {
    //    console.log()
    //    this.salucroPayType = value;

    //}

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

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

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

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

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

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