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


@Component({
    templateUrl: "./reasons.html",
})
export class ReasonPage implements OnInit, OnDestroy {
    page: Page;
    loading: boolean;
    modalRef: NgbModalRef;
    submitting: boolean;
    submitted: boolean;
    reasonForm: FormGroup;
    records: Array<Reasons>;



    constructor(
        private readonly appData: AppData,
        private readonly httpService: HttpService,
        private readonly modalService: NgbModal,
        private readonly formBuilder: FormBuilder,
        private readonly notifyService: NotifyService,
      
    ) {
        this.loading = true;
        this.page = new Page();
        this.buildForm();
        this.records = new Array<Reasons>();
      
       
    }

    private buildForm() {
        this.reasonForm = this.formBuilder.group({
            reasonsId: 0,
            reason: [null, [Validators.required, Validators.maxLength(250), WhiteSpaceValidator.isValid]],
        });
    }
    get form() { return this.reasonForm.controls; }
    onOpenModel(content: TemplateRef<any>, record?: Reasons) {
        this.buildForm();
        if (record) {
            this.reasonForm.patchValue({
                reasonsId: record.reasonsId,
                reason: record.reason
            });
        }
        this.modalRef = this.modalService.open(content, {
            backdrop: "static",
            keyboard: false,
            centered: false,
            windowClass: "custom-modal effect-scale"
        });
    }
    onCloseModal() {
        try {
            this.modalRef.close();
            this.modalRef = undefined;
        } catch (e) {
            // ignored;
        }

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

    onSubmit() {
        this.submitted = true;
        if (this.reasonForm.invalid) {
            return;
        }
        this.submitting = true;
        const request = {
            ...this.reasonForm.getRawValue(),
            createdBy: this.page.userAccount.accountId,
            modifiedBy: this.page.userAccount.accountId,
            loginRoleId: this.page.userAccount.roleId,
            createdByName: this.page.userAccount.fullName,
            modifiedByName: this.page.userAccount.fullName,
        };
        var url = ApiResources.getURI(ApiResources.reason.base, ApiResources.reason.insert);
        if (request["reasonsId"] > 0) {
            url = ApiResources.getURI(ApiResources.reason.base, ApiResources.reason.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["reasonsId"] > 0 ? 'updated' : 'added'} successfully.`);
                    }
                    if (response === -1) {
                        this.notifyService.warningToast("This Reasons  already exists.");
                        return;
                    }
                    this.onCloseModal();
                    this.fetchAll();
                },
                (error: HttpErrorResponse) => {
                    this.notifyService.errorToast(error.error);
                }
            );
    }

    onDelete(record: Reasons) {
        this.notifyService.delete(() => {
            const request = {
                reasonsId: record.reasonsId,
                reason: record.reason,
                createdBy: this.page.userAccount.accountId,
                createdByName: this.page.userAccount.fullName,
                loginRoleId: this.page.userAccount.roleId,
                modifiedByName: this.page.userAccount.fullName
            };
            this.httpService.post(ApiResources.getURI(ApiResources.reason.base, ApiResources.reason.delete), request)
                .pipe(takeUntil(this.page.unSubscribe))
                .pipe(finalize(() => this.loading = false))
                .subscribe(
                    () => {
                            this.notifyService.successToast("Record deleted successfully.");
                            this.fetchAll();
                    },
                    (error: HttpErrorResponse) => {
                        const errorMessage = UtilHelper.handleError(error);
                        if (errorMessage) {
                            this.notifyService.warning(errorMessage);
                        } else {
                            this.notifyService.defaultError();
                        }
                    }
                );
        })
    }

    onModifyStatus(reason: Reasons, status: boolean) {

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

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

    private fetchAll() {
        this.loading = true;
        const request = {
        };
        this.httpService.post(ApiResources.getURI(ApiResources.reason.base, ApiResources.reason.fetch), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loading = false))
            .subscribe(
                (response: Array<Reasons>) => {
                    this.records = response;
                },
                (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.fetchAll();
                } else {
                    this.page.userAccount = undefined;
                }
            });
    }


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