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

@Component({
    templateUrl: "./case-type.html",
    encapsulation: ViewEncapsulation.None
})
export class CaseTypePage implements OnInit, OnDestroy{
    page: Page;
    modalRef: NgbModalRef;
    submitting: boolean;
    submitted: boolean;
    caseTypeForm: FormGroup;
    loading: boolean;
    records: Array<CaseType>;
    

    constructor(
        private readonly formBuilder: FormBuilder,
        private readonly modalService: NgbModal,
        private readonly appData: AppData,
        private readonly httpService: HttpService,
        private readonly notifyService: NotifyService,
       
    ) {
        this.page = new Page();       
        this.loading = true;     
   
        this.records = new Array<CaseType>();
        
    }
    private buildForm() {
        this.caseTypeForm =  this.formBuilder.group({
            caseTypeId:0,
            caseTypeName: [null, [Validators.required, Validators.maxLength(250), WhiteSpaceValidator.isValid, Validators.pattern('^[a-zA-Z]*$')]],
            code: [null, [Validators.required, Validators.maxLength(250), WhiteSpaceValidator.isValid]],
        })
       
    }

    changeStatus(item: CaseType, status: boolean) {
        this.notifyService.confirm(`You want to ${status ? 'Activate' : 'Deactivate'} this cast type?`, () => {

            const request = {
                caseTypeId: item.caseTypeId,
                caseTypeName: item.caseTypeName,
                code: item.code,
                modifiedBy: this.page.userAccount.accountId,
                loginRoleId: this.page.userAccount.roleId,
                modifiedByName: this.page.userAccount.fullName,
                active: status
            };

            var url = ApiResources.getURI(ApiResources.caseType.base, ApiResources.caseType.modifyStatus);
            this.httpService.post(url, request)
                .subscribe(
                    (response: number) => {
                        if (response > 0) {
                            this.notifyService.successToast(`Record ${request["caseTypeId"] > 0 ? 'updated' : 'added'} successfully.`);
                            this.fetchAll();
                        }
                        if (response === -1) {
                            this.notifyService.warningToast("This caseType Name already exists.");
                            return;
                        }
                    },
                    (error: HttpErrorResponse) => {
                        this.notifyService.errorToast(error.error);
                    }
            );
        })
            
    }

    onOpenModel(content: TemplateRef<any>, record?: CaseType) {
        this.buildForm();
        if (record) {
            this.caseTypeForm.patchValue({
                caseTypeId: record.caseTypeId,
                caseTypeName: record.caseTypeName,
                code: record.code,
            });
        }

        this.modalRef = this.modalService.open(content, {
            backdrop: "static",
            keyboard: false,
            centered: false,
            size: 'lg',
            windowClass: "custom-modal effect-scale"
        });
    }
    get form() { return this.caseTypeForm.controls; }

    onSubmit() {
        this.submitted = true;
        if (this.caseTypeForm.invalid) {
            return;
        }
        this.submitting = true;
        const request = {
            ...this.caseTypeForm.getRawValue(),
            createdBy: this.page.userAccount.accountId,
            loginRoleId: this.page.userAccount.roleId,
            createdByName: this.page.userAccount.fullName
        };
        console.log("The case type request is : " + JSON.stringify(request));
        var url = ApiResources.getURI(ApiResources.caseType.base, ApiResources.caseType.insert);
        if (request["caseTypeId"] > 0) {
            url = ApiResources.getURI(ApiResources.caseType.base, ApiResources.caseType.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["caseTypeId"] > 0 ? 'updated' : 'added'} successfully.`);
                        this.fetchAll();
                    }
                    if (response === -1) {
                        this.notifyService.warningToast("This caseType Name already exists.");
                        return;
                    }
                    this.onCloseModal();
                    
                },
                //(error: HttpErrorResponse) => {
                //   // this.onError(error);
                //}
            );
    }

    private fetchAll() {
        this.loading = true;
        const request = {
           
            
        };
        this.httpService.post(ApiResources.getURI(ApiResources.caseType.base, ApiResources.caseType.fetch), request)
            .pipe(takeUntil(this.page.unSubscribe))
            .pipe(finalize(() => this.loading = false))
            .subscribe(
                (response: Array<CaseType>) => {
                    this.records = response;
                    //UtilHelper.applyPagination(this.records);
                },
                //(error: HttpErrorResponse) => {
                //    this.onError(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.page.unsubscribeAll();
    }
    onCloseModal() {
        try {
            this.modalRef.close();
            this.modalRef = undefined;
        } catch (e) {
            // ignored;
        }

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