import { Component, OnDestroy, OnInit, ViewEncapsulation, TemplateRef } from "@angular/core";
import { Roles } from "@shared/entities";
import { ApiResources, UtilHelper } from "@shared/helpers";
import { AppData, HttpService, NotifyService, ResourceService } 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, IResource } from "@shared/models";
import { WhiteSpaceValidator } from "../../../../../shared/validators";

class TrackBy {
    role(item: Roles) {
        return item.roleId;
    }
}

class FilterOptions {
    roleId: number;
    active: boolean = null;
}

class Filters {
    options: FilterOptions;
    applied: boolean;

    constructor() {
        this.init();
    }

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

@Component({
    templateUrl: "./roles.html",
    encapsulation: ViewEncapsulation.None
})
export class RolePage implements OnInit, OnDestroy {
    page: Page;
    filters: Filters;
    trackBy: TrackBy;
    pagination: Pagination;
    loading: boolean;
    roles: Array<Roles>;
    selectedRole: Roles;
    roleNames: Array<IResource>;
    modalRef: NgbModalRef;
    roleForm: FormGroup;
    submitting: boolean;
    submitted: boolean;
    loadingRoles: 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,
        private readonly resourceService: ResourceService
    ) {
        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 fetchRoles() {
        const request = Object.assign(UtilHelper.clone(this.filters.options), UtilHelper.clone(this.pagination));
        this.httpService.post<Array<Roles>>(ApiResources.getURI(ApiResources.role.base, ApiResources.role.fetch), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loading = false))
            .subscribe((response: Array<Roles>) => {
                this.roles = response;
                UtilHelper.applyPagination(this.roles, this.pagination);
            });
    }

    private fetchRoleNames() {
        this.resourceService.roles()
            .pipe(takeUntil(this.page.unSubscribe))
            .subscribe((response: Array<IResource>) => {
                this.roleNames = response;
            });
    }

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

    private updateForm() {
        this.roleForm.patchValue({
            roleId: this.selectedRole.roleId,
            roleName: this.selectedRole.roleName,
            active: this.selectedRole.active
        });
    }

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

        if (role) {
            this.selectedRole = role;
            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.roleForm.valid) {
            return;
        }

        this.submitting = true;
        const request = Object.assign(UtilHelper.clone(this.roleForm.getRawValue()));
        request["createdByName"] = this.page.userAccount.fullName;
        if (this.roleForm.value.roleId === 0) {
            request.createdBy = this.page.userAccount.accountId;
            request.createdByName = this.page.userAccount.fullName;
            this.httpService.post(ApiResources.getURI(ApiResources.role.base, ApiResources.role.add), request)
                .pipe(takeUntil(this.page.unSubscribe))
                .pipe(finalize(() => {
                    this.submitting = false;
                    this.submitted = false;
                }))
                .subscribe(() => {
                    this.onCloseModal();
                    this.fetchRoleNames();
                    this.fetchRoles();
                    this.notifyService.successToast("Role 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.role.base, ApiResources.role.update), request)
                .pipe(takeUntil(this.page.unSubscribe))
                .pipe(finalize(() => {
                    this.submitting = false;
                    this.submitted = false;
                }))
                .subscribe(() => {
                    this.onCloseModal();
                    this.fetchRoleNames();
                    this.fetchRoles();
                    this.notifyService.successToast("Role details has been updated successfully.");
                }, (error: HttpErrorResponse) => {
                    const errorMessage = UtilHelper.handleError(error);
                    if (errorMessage) {
                        this.notifyService.warning(errorMessage);
                    } else {
                        this.notifyService.defaultError();
                    }
                });
        }
    }

    onModifyStatus(item: Roles, status: boolean) {
        this.notifyService.confirm(`You want to ${status ? 'Activate' : 'Deactivate'} this role?`, () => {
            const request = {
                createdBy: this.page.userAccount.accountId,
               modifiedBy: this.page.userAccount.accountId,
                active: status,
                roleId: item.roleId,
                roleName: item.roleName,
                createdByName: this.page.userAccount.fullName,
                createdByRole: this.page.userAccount.roleName,
                loginRoleId: this.page.userAccount.roleId,
                modifiedByName: this.page.userAccount.fullName,
                modifiedByRole: this.page.userAccount.roleName,
            };

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

    //onDelete(role: Roles) {
    //    debugger;
    //    const request = {
    //        roleId: role.roleId,
    //        modifiedBy: this.page.userAccount.accountId,
    //        roleName: role.roleName
    //    }
    //    this.notifyService.delete(() => {
    //        this.httpService
    //            .post(ApiResources.getURI(ApiResources.role.base, ApiResources.role.delete), request)
    //            .pipe(takeUntil(this.page.unSubscribe))
    //            .pipe(finalize(() => { }))
    //            .subscribe(
    //                () => {
    //                    this.notifyService.successToast("Role deleted successfully.");
    //                    this.fetchRoles();
    //                }
    //            );
    //    }, () => { });
    //}

    get form() {
        return this.roleForm.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.fetchRoles();
    }

    onShowFilters() {
        $("body").addClass("right-bar-enabled");
    }

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

    onResetFilters() {
        this.filters.init();
        this.loading = true;
        this.fetchRoles();
        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.fetchRoles();
                    this.fetchRoleNames();
                } else {
                    this.page.userAccount = undefined;
                }
            });
    }

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