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 { AssessmentType } from "@shared/entities/assessment-type.entity";
import { WhiteSpaceValidator } from "../../../../../shared/validators";

class TrackBy {
    assessmentType(item: AssessmentType) {
        return item.assessmentTypeId;
    }
}

class FilterOptions {
    name: string = null;
    assessmentTypeId: number;
}

class Filters {
    options: FilterOptions;
    applied: boolean;

    constructor() {
        this.init();
    }

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

@Component({
    templateUrl: "./assessment-type.html",
    encapsulation: ViewEncapsulation.None
})
export class AssessmentTypePage implements OnInit, OnDestroy {
    page: Page;
    filters: Filters;
    trackBy: TrackBy;
    pagination: Pagination;
    assessmentTypeForm: FormGroup;
    loading: boolean;
    assessmentType: Array<AssessmentType>;
    selectedAssessmentType: AssessmentType

    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.assessmentTypeForm = this.formBuilder.group({
            assessmentTypeId: 0,
            name: [null, [Validators.required, WhiteSpaceValidator.isValid]]
        });
    }  

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

        if (assessmentType) {
            this.selectedAssessmentType = assessmentType;
            this.updateForm();
        }

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

    fetchAddAssessmentType() {
        this.loading = true;

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

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

    onSubmit() {
        this.submitted = true;

        if (!this.assessmentTypeForm.valid) {
            return;
        }
        this.submitting = true;
        const request = Object.assign(UtilHelper.clone(this.assessmentTypeForm.getRawValue()));
        if (Number(this.assessmentTypeForm.value.assessmentTypeId) === 0) {
            request.createdBy = this.page.userAccount.accountId;
            request.createdByName = this.page.userAccount.fullName;
            this.httpService.post(ApiResources.getURI(ApiResources.assessmentType.base, ApiResources.assessmentType.add), request)
                .pipe(takeUntil(this.page.unSubscribe))
                .pipe(finalize(() => {
                    this.submitting = false;
                    this.submitted = false;
                }))
                .subscribe(() => {
                    this.onCloseModal();
                    this.fetchAddAssessmentType();
                    this.notifyService.success("Assessment 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.assessmentType.base, ApiResources.assessmentType.update), request)
                .pipe(takeUntil(this.page.unSubscribe))
                .pipe(finalize(() => {
                    this.submitting = false;
                    this.submitted = false;
                }))
                .subscribe(() => {
                    this.onCloseModal();
                    this.fetchAddAssessmentType();
                    this.notifyService.success("Assessment 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.assessmentTypeForm.controls;
    }    

    private updateForm() {
        this.assessmentTypeForm.patchValue({
            assessmentTypeId: this.selectedAssessmentType.assessmentTypeId,
            name: this.selectedAssessmentType.name
        });
    }  

    onDelete(assessmentType: AssessmentType) {
        
        this.notifyService.delete(() => {
            this.httpService
                .post(ApiResources.getURI(ApiResources.assessmentType.base, ApiResources.assessmentType.delete), {
                    assessmentTypeId: assessmentType.assessmentTypeId, 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("Assessment Type deleted successfully.");
                        this.fetchAddAssessmentType();
                    }
                );
        }, () => { });
    }

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

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

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

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