var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { DialogProxyTools } from "../proxy/DialogProxyTools";
import { RecordSetVisitor } from "../proxy/RecordSetVisitor";
import { RecordVisitor } from "../proxy/RecordVisitor";
import { SessionVisitor } from "../proxy/SessionVisitor";
import { storage as clientStorage } from "../storage";
import { BriefcaseVisitor } from "./BriefcaseVisitor";
import { Briefcase_Briefcase_Details_RECORD } from "./samples/Briefcase_Briefcase_Details_RECORD";
import { SdaDialogDelegateStateVisitor } from "./SdaDialogDelegateStateVisitor";
// @FIX_THIS
// remove this:
const storage = clientStorage;
// uncomment this
// const storage = clientStorage.getSecureInstance();
// Set the secret key like this:
// storage.secretKey = 'secret_key';
export class SdaDialogDelegateTools {
    static constructAddToBriefcaseNullRedirection(tenantId, sessionId, referringDialogId) {
        const nullRedirectionId = DialogProxyTools.constructNullRedirectionId();
        return {
            "tenantId": tenantId,
            "referringObject": {
                "dialogMode": "LIST",
                "dialogAlias": "Workpackage_AddToBriefcase_FORM",
                "actionId": "alias_AddToBriefcase",
                "type": "hxgn.api.dialog.ReferringDialog",
                "dialogId": referringDialogId
            },
            "refreshNeeded": true,
            "sessionId": sessionId,
            "id": nullRedirectionId,
            "type": "hxgn.api.dialog.NullRedirection"
        };
    }
    static constructBriefcaseEnterOfflineDetailsNullRedirection(tenantId, sessionId, refreshNeeded) {
        const nullRedirectionId = DialogProxyTools.constructNullRedirectionId();
        // TODO: What should a ReferringDialog contain as an action id when the action is a 'PUT viewMode'?
        return {
            "tenantId": tenantId,
            "referringObject": {
                "dialogMode": "DESTROYED",
                "dialogName": this.BRIEFCASE_ENTER_OFFLINE_DETAILS_DIALOG_NAME,
                "dialogAlias": this.BRIEFCASE_ENTER_OFFLINE_DETAILS_DIALOG_NAME,
                "type": "hxgn.api.dialog.ReferringDialog",
                "dialogId": this.BRIEFCASE_ENTER_OFFLINE_DETAILS_DIALOG_ID
            },
            "refreshNeeded": refreshNeeded,
            "sessionId": sessionId,
            "id": nullRedirectionId,
            "type": "hxgn.api.dialog.NullRedirection"
        };
    }
    static constructExitOfflineModeNullRedirection(tenantId, sessionId) {
        const nullRedirectionId = DialogProxyTools.constructNullRedirectionId();
        return {
            "tenantId": tenantId,
            "referringObject": {
                "dialogMode": "READ",
                "dialogAlias": "Briefcase_Briefcase_Details",
                "actionId": this.EXIT_OFFLINE_MODE_MENU_ACTION_ID,
                "type": "hxgn.api.dialog.ReferringDialog",
                "dialogId": this.BRIEFCASE_DETAILS_DIALOG_ID
            },
            "refreshNeeded": true,
            "sessionId": sessionId,
            "id": nullRedirectionId,
            "type": "hxgn.api.dialog.NullRedirection"
        };
    }
    static constructOfflineLogoutResponse(sessionId) {
        return {
            "sessionId": sessionId,
            "type": this.SESSION_ID_MODEL_TYPE
        };
    }
    static constructRemoveFromBriefcaseNullRedirection(tenantId, sessionId, referringDialogId) {
        const nullRedirectionId = DialogProxyTools.constructNullRedirectionId();
        return {
            "tenantId": tenantId,
            "referringObject": {
                "dialogMode": "LIST",
                "dialogAlias": "Workpackage_RemoveFromBriefcase_FORM",
                "actionId": "alias_RemoveFromBriefcase",
                "type": "hxgn.api.dialog.ReferringDialog",
                "dialogId": referringDialogId
            },
            "refreshNeeded": true,
            "sessionId": sessionId,
            "id": nullRedirectionId,
            "type": "hxgn.api.dialog.NullRedirection"
        };
    }
    static createOfflineLoginHash(tenantId, sessionId, userId, password) {
        const source = `OFFLINE_LOGIN:${tenantId}/${sessionId}/${userId}/${password}`;
        // TODO: insert crypto hashing here
        return source;
    }
    static isBriefcaseEnterOfflineDetailsDialogId(dialogId) {
        return dialogId === this.BRIEFCASE_ENTER_OFFLINE_DETAILS_DIALOG_ID;
    }
    static isBriefcaseEnterOfflineDialogId(dialogId) {
        return dialogId === this.BRIEFCASE_ENTER_OFFLINE_ROOT_DIALOG_ID;
    }
    static isBriefcaseWorkbenchActionRequest(dialogRequest) {
        return dialogRequest.isPostWorkbenchActionPathWithActionId(SdaDialogDelegateTools.BRIEFCASE_WORKBENCH_ACTION_ID);
    }
    static isEnterOfflineModeMenuActionRequest(dialogRequest) {
        return dialogRequest.isPostMenuActionPathWithActionId(SdaDialogDelegateTools.ENTER_OFFLINE_MODE_MENU_ACTION_ID);
    }
    static isExitOfflineModeMenuActionRequest(dialogRequest) {
        return dialogRequest.isPostMenuActionPathWithActionId(SdaDialogDelegateTools.EXIT_OFFLINE_MODE_MENU_ACTION_ID);
    }
    static isOfflineBriefcaseCommentsRecordSetRequest(dialogRequest) {
        return dialogRequest.isPostRecordsPathWithDialogId(this.BRIEFCASE_COMMENTS_DIALOG_ID);
    }
    static isOfflineBriefcaseDialogId(dialogId) {
        return dialogId === this.BRIEFCASE_ROOT_DIALOG_ID;
    }
    static isOfflineBriefcaseDetailsDialogId(dialogId) {
        return dialogId === this.BRIEFCASE_DETAILS_DIALOG_ID;
    }
    static isOfflineBriefcaseWorkPackagesDialogId(dialogId) {
        return dialogId === this.BRIEFCASE_WORK_PACKAGES_DIALOG_ID;
    }
    static isOfflineBriefcaseWorkPackagesRequest(dialogRequest) {
        if (!dialogRequest.isPostRecordsPath()) {
            return false;
        }
        const pathFields = dialogRequest.deconstructPostRecordsPath();
        return SdaDialogDelegateTools.isOfflineBriefcaseWorkPackagesDialogId(pathFields.dialogId);
    }
    static isOfflineDocumentsPropertiesDialogId(dialogId) {
        return dialogId.startsWith(this.OFFLINE_DOCUMENTS_DIALOG_PROPERTIES_ID_PREFIX);
    }
    static isOfflineTagsPropertiesDialogId(dialogId) {
        return dialogId.startsWith(this.OFFLINE_TAGS_DIALOG_PROPERTIES_ID_PREFIX);
    }
    static isWorkPackagesAddToBriefcaseMenuActionRequest(dialogRequest) {
        return dialogRequest.isPostMenuActionPathWithActionId(SdaDialogDelegateTools.ADD_TO_BRIEFCASE_MENU_ACTION_ID);
    }
    static isWorkPackagesListRecordSet(dialogRequest, jsonObject) {
        if (!dialogRequest.isPostRecordsPath()) {
            return false;
        }
        if (!jsonObject || !jsonObject.type || !jsonObject.dialogName) {
            return false;
        }
        return jsonObject.type === this.RECORD_SET_MODEL_TYPE &&
            jsonObject.dialogName === this.WORK_PACKAGES_LIST_DIALOG_NAME;
    }
    static isWorkPackagesRemoveFromBriefcaseMenuActionRequest(dialogRequest) {
        if (!dialogRequest.isPostMenuActionPath()) {
            return false;
        }
        const pathFields = dialogRequest.deconstructPostMenuActionPath();
        return pathFields.actionId === SdaDialogDelegateTools.REMOVE_FROM_BRIEFCASE_MENU_ACTION_ID;
    }
    static isWorkPackagesRootDialog(jsonObject) {
        if (!jsonObject || !jsonObject.type || !jsonObject.dialogName) {
            return false;
        }
        return jsonObject.type === this.EDITOR_DIALOG_MODEL_TYPE &&
            jsonObject.dialogName === this.WORK_PACKAGES_ROOT_DIALOG_NAME;
    }
    static insertBriefcaseMetaDataIntoWorkPackagesDialog(originalDialog) {
        const workPackagesQueryDialog = originalDialog.children[0];
        const propertyDefs = workPackagesQueryDialog.recordDef.propertyDefs;
        propertyDefs.push({
            "writeAllowed": false,
            "propertyName": "briefcase",
            "canCauseSideEffects": false,
            "upperCaseOnly": false,
            "propertyType": "boolean",
            "type": "hxgn.api.dialog.PropertyDef",
            "writeEnabled": false
        });
        const columns = workPackagesQueryDialog.view.columns;
        columns.push({
            "propertyName": "briefcase",
            "heading": "Briefcase",
            "type": "hxgn.api.dialog.Column"
        });
        // Return original dialog WITH patches
        return originalDialog;
    }
    static readDialogDelegateStateKeys(tenantId) {
        return __awaiter(this, void 0, void 0, function* () {
            const keys = yield storage.getAllKeys();
            const dialogDelegateStateKeysForTenant = [];
            for (const k of keys) {
                if (k.endsWith(this.DIALOG_DELEGATE_STATE_KEY_SUFFIX) && k.includes(`.${tenantId}.`)) {
                    dialogDelegateStateKeysForTenant.push(k);
                }
            }
            return dialogDelegateStateKeysForTenant;
        });
    }
    static readDialogDelegateStateVisitor(tenantId, userId) {
        const key = this.createStorageKey(tenantId, userId, this.DIALOG_DELEGATE_STATE_KEY);
        return storage.getJson(key).then(jsonObject => {
            if (!jsonObject) {
                const briefcase = Briefcase_Briefcase_Details_RECORD.copyOfResponse();
                BriefcaseVisitor.visitAndSetOnline(briefcase, true);
                jsonObject = {
                    briefcase: Briefcase_Briefcase_Details_RECORD.copyOfResponse(),
                    selectedWorkPackageIds: [],
                    userId: null,
                    workPackages: RecordSetVisitor.emptyRecordSetVisitor().enclosedJsonObject(),
                    mobileComments: RecordSetVisitor.emptyRecordSetVisitor().enclosedJsonObject()
                };
                // // Log.info('SdaDialogDelegateTools::readDelegateState -- returning defaults: ' + JSON.stringify(jsonObject));
            }
            return new SdaDialogDelegateStateVisitor(jsonObject);
        });
    }
    static readOfflineDocumentsPropertiesRecord(tenantId, userId, dialogId) {
        const key = `${userId}.${tenantId}.ppm.sda.workPackages.documents.dialog.${dialogId}.record`;
        return storage.getJson(key).then(jsonObject => new RecordVisitor(jsonObject));
    }
    static readOfflineSession(tenantId, userId) {
        const key = this.createStorageKey(tenantId, userId, this.OFFLINE_SESSION_KEY);
        return storage.getJson(key).then(jsonObject => new SessionVisitor(jsonObject));
    }
    static readOfflineTagsPropertiesRecord(tenantId, userId, dialogId) {
        const key = `${userId}.${tenantId}.ppm.sda.workPackages.tags.dialog.${dialogId}.record`;
        return storage.getJson(key).then(jsonObject => new RecordVisitor(jsonObject));
    }
    static startsWithBriefcaseRootDialogId(dialogId) {
        return dialogId.startsWith(this.BRIEFCASE_ROOT_DIALOG_ID);
    }
    static writeDialogDelegateState(tenantId, stateVisitor) {
        const userId = stateVisitor.visitUserId();
        const key = this.createStorageKey(tenantId, userId, this.DIALOG_DELEGATE_STATE_KEY);
        return storage.setJson(key, stateVisitor.enclosedJsonObject());
    }
    static writeOfflineSession(tenantId, userId, offlineSessionVisitor) {
        const key = this.createStorageKey(tenantId, userId, this.OFFLINE_SESSION_KEY);
        return storage.setJson(key, offlineSessionVisitor.enclosedJsonObject());
    }
    static createStorageKey(tenantId, userId, keyTemplate) {
        const key = keyTemplate.replace('${tenantId}', tenantId);
        return key.replace('${userId}', userId);
    }
}
// Briefcase Dialog Ids
SdaDialogDelegateTools.BRIEFCASE_ROOT_DIALOG_ID = 'briefcase';
SdaDialogDelegateTools.BRIEFCASE_COMMENTS_DIALOG_ID = SdaDialogDelegateTools.BRIEFCASE_ROOT_DIALOG_ID + '_comments';
SdaDialogDelegateTools.BRIEFCASE_DETAILS_DIALOG_ID = SdaDialogDelegateTools.BRIEFCASE_ROOT_DIALOG_ID + '_details';
SdaDialogDelegateTools.BRIEFCASE_WORK_PACKAGES_DIALOG_ID = SdaDialogDelegateTools.BRIEFCASE_ROOT_DIALOG_ID + '_workPackages';
SdaDialogDelegateTools.BRIEFCASE_ENTER_OFFLINE_DETAILS_DIALOG_ID = SdaDialogDelegateTools.BRIEFCASE_ROOT_DIALOG_ID + '_enter_offline_details';
SdaDialogDelegateTools.BRIEFCASE_ENTER_OFFLINE_ROOT_DIALOG_ID = SdaDialogDelegateTools.BRIEFCASE_ROOT_DIALOG_ID + '_enter_offline';
// Dialog Names
SdaDialogDelegateTools.BRIEFCASE_DETAILS_DIALOG_NAME = 'Briefcase_Briefcase_Details';
SdaDialogDelegateTools.BRIEFCASE_MOBILE_COMMENTS_DIALOG_NAME = 'Briefcase_Briefcase_MobileComments';
SdaDialogDelegateTools.BRIEFCASE_ROOT_DIALOG_NAME = 'Briefcase_Briefcase_FORM';
SdaDialogDelegateTools.BRIEFCASE_WORK_PACKAGES_DIALOG_NAME = 'Briefcase_Briefcase_Workpackages';
SdaDialogDelegateTools.BRIEFCASE_ENTER_OFFLINE_DETAILS_DIALOG_NAME = 'Briefcase_EnterOfflineMode';
SdaDialogDelegateTools.DOCUMENTS_LIST_DIALOG_NAME = 'Workpackage_Documents_Documents';
SdaDialogDelegateTools.DOCUMENTS_PROPERTIES_DIALOG_NAME = 'Workpackage_Documents_Properties';
SdaDialogDelegateTools.DOCUMENTS_ROOT_DIALOG_NAME = 'Workpackage_Documents_FORM';
SdaDialogDelegateTools.MOBILE_COMMENT_DETAILS_PROPERTIES_DIALOG_NAME = 'MobileComment_Details_Properties';
SdaDialogDelegateTools.MOBILE_COMMENT_DETAILS_ROOT_DIALOG_NAME = 'MobileComment_Details_FORM';
SdaDialogDelegateTools.MOBILE_COMMENT_IMAGE_NOT_AVAILABLE_DETAILS_DIALOG_ID = 'image_not_available_details';
SdaDialogDelegateTools.MOBILE_COMMENT_IMAGE_NOT_AVAILABLE_DETAILS_DIALOG_NAME = 'MobileComment_ImageNotAvailable';
SdaDialogDelegateTools.MOBILE_COMMENT_IMAGE_NOT_AVAILABLE_ROOT_DIALOG_ID = 'image_not_available';
SdaDialogDelegateTools.MOBILE_COMMENT_IMAGE_NOT_AVAILABLE_ROOT_DIALOG_NAME = 'MobileComment_ImageNotAvailable_FORM';
SdaDialogDelegateTools.MOBILE_COMMENT_COMMENT_NOT_AVAILABLE_DETAILS_DIALOG_ID = 'comment_not_available_details';
SdaDialogDelegateTools.MOBILE_COMMENT_COMMENT_NOT_AVAILABLE_DETAILS_DIALOG_NAME = 'MobileComment_CommentNotAvailable';
SdaDialogDelegateTools.MOBILE_COMMENT_COMMENT_NOT_AVAILABLE_ROOT_DIALOG_ID = 'comment_not_available';
SdaDialogDelegateTools.MOBILE_COMMENT_COMMENT_NOT_AVAILABLE_ROOT_DIALOG_NAME = 'MobileComment_CommentNotAvailable_FORM';
SdaDialogDelegateTools.TAGS_ROOT_DIALOG_NAME = 'Workpackage_Tags_FORM';
SdaDialogDelegateTools.TAGS_PROPERTIES_DIALOG_NAME = 'Workpackage_Tags_Properties';
SdaDialogDelegateTools.TAGS_LIST_DIALOG_NAME = 'Workpackage_Tags_Tags';
SdaDialogDelegateTools.TAG_DETAILS_ROOT_DIALOG_NAME = 'Tag_Details_FORM';
SdaDialogDelegateTools.TAG_DETAILS_PROPERTIES_DIALOG_NAME = 'Tag_Details_Properties';
SdaDialogDelegateTools.TAG_DETAILS_LIST_DIALOG_NAME = 'Tag_Details_Documents';
SdaDialogDelegateTools.WORK_PACKAGES_LIST_DIALOG_NAME = 'Workpackage_General';
SdaDialogDelegateTools.WORK_PACKAGES_ROOT_DIALOG_NAME = 'Workpackage_General_FORM';
// Dynamic Dialog Ids -- PRIVATE
SdaDialogDelegateTools.OFFLINE_DOCUMENTS_DIALOG_PROPERTIES_ID_PREFIX = 'offline_documents_properties_';
SdaDialogDelegateTools.OFFLINE_TAGS_DIALOG_PROPERTIES_ID_PREFIX = 'offline_tags_properties_';
// Action Ids
SdaDialogDelegateTools.ADD_TO_BRIEFCASE_MENU_ACTION_ID = 'alias_AddToBriefcase';
SdaDialogDelegateTools.BRIEFCASE_WORKBENCH_ACTION_ID = 'Briefcase';
SdaDialogDelegateTools.ENTER_OFFLINE_MODE_MENU_ACTION_ID = 'alias_EnterOfflineMode';
SdaDialogDelegateTools.EXIT_OFFLINE_MODE_MENU_ACTION_ID = 'alias_ExitOfflineMode';
SdaDialogDelegateTools.REMOVE_FROM_BRIEFCASE_MENU_ACTION_ID = 'alias_RemoveFromBriefcase';
// Model Types
SdaDialogDelegateTools.EDITOR_DIALOG_MODEL_TYPE = 'hxgn.api.dialog.EditorDialog';
SdaDialogDelegateTools.RECORD_SET_MODEL_TYPE = 'hxgn.api.dialog.RecordSet';
SdaDialogDelegateTools.SESSION_ID_MODEL_TYPE = 'hxgn.api.dialog.SessionId';
// Storage Keys
SdaDialogDelegateTools.DIALOG_DELEGATE_STATE_KEY_SUFFIX = 'SdaDialogDelegate.delegatestate';
SdaDialogDelegateTools.DIALOG_DELEGATE_STATE_KEY = '${userId}.${tenantId}.' + SdaDialogDelegateTools.DIALOG_DELEGATE_STATE_KEY_SUFFIX;
SdaDialogDelegateTools.OFFLINE_SESSION_KEY = '${userId}.${tenantId}.offlinesession';
