import { ListRecordsCriteria, FieldQuery, Pagination, Record } from "../../Models";
import { LoadingService } from "../../Services/LoadingService";
import { DynamicRecordService } from "../../Services/DynamicRecordService";
import { CachingService } from "../../Services";

export class CorrespondenceActions {
    private record: Record = new Record();
    private correspondenceActions: any[];
    public ApprovalEntries: any[];
    public RecordStatus: number;
    private postGetActionPermissions: any;
    private _loadingService = new LoadingService();
    private _dynamicRecordService: DynamicRecordService = new DynamicRecordService();
    private _loggedInUser: any;
    private _cachingService = new CachingService();

    constructor(record: Record, recordStatus: number, postGetActionPermissions: any) {
        this.record = record;
        this.postGetActionPermissions = postGetActionPermissions;
        this.RecordStatus = recordStatus;

        this._loggedInUser = this._cachingService.read('LoggedInUser');

        this.getCorrespondenceActions();
    }

    private getCorrespondenceActions() {
        if (this.record.id) {
            let criteria: ListRecordsCriteria = new ListRecordsCriteria();
            criteria.asLookup = false;
            criteria.entityId = 28;
            criteria.query = new Array<FieldQuery>();
            let query = new FieldQuery();
            query.fieldId = 280;
            query.value = this.record.id.toString();
            criteria.query.push(query);
            criteria.pagination = new Pagination();
            criteria.pagination.start = 0;
            criteria.pagination.count = 99999;

            this._loadingService.show();
            this._dynamicRecordService.listRecords(criteria).then(
                (result: any) => {
                    this._loadingService.hide();
                    console.log(result);

                    // this.state.reasonLookups = result;
                    this.correspondenceActions = result;

                    if (this.postGetActionPermissions)
                        this.postGetActionPermissions();
                },
                error => {
                    // alert(error.text());
                    // this.toastr.error('', error.text());
                    //this.displayAlertModal(error.text());
                    alert(error);
                    this._loadingService.hide();
                }
            );
        }
    }

    isActionAuthorized(actionName: string): boolean {
        let isAuthorized: boolean = false;

        if (actionName == 'Forward')
            return this.isForwardActionAuthorized();

        if (actionName == 'Approve')
            return this.isApproveActionAuthorized();

        if (actionName == 'Reject')
            return this.isRejectActionAuthorized();

        if (actionName == 'ReplyNew')
            return this.isReplyNewActionAuthorized();

        if (actionName == 'Sign')
            return this.isSignActionAuthorized();

        if (actionName == 'Close')
            return this.isCloseActionAuthorized();

        if (actionName == 'ReOpen')
            return this.isReOpenActionAuthorized();

        if (actionName == 'Archive')
            return this.isArchiveActionAuthorized();

        if (actionName == 'ExportExternal')
            return this.isExportExternalActionAuthorized();

        if (actionName == 'UpdateLetterDetails')
            return this.isUpdateLetterDetailsActionAuthorized();

        return isAuthorized;
    }

    isForwardActionAuthorized(): boolean {
        let initiator = 0;

        this.record.fields.forEach((field: any) => {
            if (field.id == 197) {
                initiator = field.data;
            }
        })

        if ((initiator == this._loggedInUser.id && this.RecordStatus == 22) || this.RecordStatus == 106)
            return true;

        return false;
    }

    isApproveActionAuthorized(): boolean {
        if (!this.isActionPresentInActionsList('Approve'))
            return false;

        if (this.ApprovalEntries != null) {
            let isAlreadyApproved: any;
            this.ApprovalEntries.forEach((approvalEntry: any) => {
                if (approvalEntry.CreatedBy == this._loggedInUser.id)
                    isAlreadyApproved = true;
            })

            if (isAlreadyApproved == true)
                return false;
        }

        return true;
    }

    isRejectActionAuthorized(): boolean {
        if (!this.isActionPresentInActionsList('Reject'))
            return false;

        if (this.ApprovalEntries != null) {
            let isAlreadyApproved: any;
            this.ApprovalEntries.forEach((approvalEntry: any) => {
                if (approvalEntry.CreatedBy == this._loggedInUser.id)
                    isAlreadyApproved = true;
            })

            if (isAlreadyApproved == true)
                return false;
        }

        return true;
    }

    isSignActionAuthorized(): boolean {

        let initiator = 0;

        this.record.fields.forEach((field: any) => {
            if (field.id == 197) {
                initiator = field.data;
            }
        })

        if ((initiator == this._loggedInUser.id || this.isActionPresentInActionsList('Sign')) && this.RecordStatus == 106)
            return true;

        return false;
    }

    isReplyNewActionAuthorized(): boolean {
        if (this.isActionPresentInActionsList('ReplyNew') && this.RecordStatus == 106)
            return true;

        return false;
    }

    isCloseActionAuthorized(): boolean {
        let initiator = 0;

        this.record.fields.forEach((field: any) => {
            if (field.id == 197) {
                initiator = field.data;
            }
        })

        if (initiator == this._loggedInUser.id && this.RecordStatus == 106)
            return true;

        return false;
    }

    isReOpenActionAuthorized(): boolean {
        let initiator = 0;

        this.record.fields.forEach((field: any) => {
            if (field.id == 197) {
                initiator = field.data;
            }
        })

        if (initiator == this._loggedInUser.id && this.RecordStatus == 62)
            return true;

        return false;
    }

    isArchiveActionAuthorized(): boolean {
        let initiator = 0;

        this.record.fields.forEach((field: any) => {
            if (field.id == 197) {
                initiator = field.data;
            }
        })

        if (initiator == this._loggedInUser.id && (this.RecordStatus == 62 || this.RecordStatus == 104))
            return true;

        return false;
    }

    isExportExternalActionAuthorized(): boolean {

        var exportExternalSg;
        this._loggedInUser.securityGroups.forEach((sg: any) => {
            if (sg.id == 6) {
                exportExternalSg = true;
            }
        });

        if (exportExternalSg == true && (this.RecordStatus == 62 || this.RecordStatus == 106))
            return true;

        return false;
    }

    isUpdateLetterDetailsActionAuthorized(): boolean {

        let initiator = 0;

        this.record.fields.forEach((field: any) => {
            if (field.id == 197) {
                initiator = field.data;
            }
        })

        if (initiator == this._loggedInUser.id && (this.RecordStatus == 106))
            return true;

        return false;
    }

    isActionPresentInActionsList(actionName: string): boolean {
        let isPresent: boolean = false;

        if (this.correspondenceActions) {
            this.correspondenceActions.forEach((action: any) => {
                if (action.Name == actionName)
                    isPresent = true;
            });
        }

        return isPresent;
    }

}