var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    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) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
import { getAccessToken, RequestAction, sendRequestFromCustomSandbox, sendWorkflowRequest, startProcessFromQuery, startProcessInstance } from '@reltio/mdm-sdk';
var validateParams = function (validationUrl, permissions) {
    if (!validationUrl)
        return { errorMessage: 'URL is empty' };
    var allowed = permissions === null || permissions === void 0 ? void 0 : permissions.some(function (permission) {
        var _a;
        var urlOrigin = (_a = validationUrl.match(/^(https?:\/\/[^:/?#]*).*$/)) === null || _a === void 0 ? void 0 : _a[1];
        var permRegex = new RegExp('^' + permission + '$');
        var decodedPerm = permission.replace(/\/*$/, '');
        return (decodedPerm === validationUrl ||
            (urlOrigin && urlOrigin === decodedPerm) ||
            ((decodedPerm === null || decodedPerm === void 0 ? void 0 : decodedPerm.startsWith('/')) && (validationUrl === null || validationUrl === void 0 ? void 0 : validationUrl.startsWith(decodedPerm))) ||
            (permission && permRegex.test(validationUrl)));
    });
    if (!allowed || ((permissions === null || permissions === void 0 ? void 0 : permissions.length) || 0) === 0) {
        return { errorMessage: 'Not enough permissions' };
    }
    return false;
};
var getAuthHeaders = function (headers, servicesPath) { return __awaiter(void 0, void 0, void 0, function () {
    var accessToken;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4 /*yield*/, getAccessToken({ servicesPath: servicesPath })];
            case 1:
                accessToken = (_a.sent()).accessToken;
                return [2 /*return*/, accessToken ? __assign(__assign({}, headers), { Authorization: "Bearer ".concat(accessToken) }) : headers];
        }
    });
}); };
export var processRequest = function (_a) {
    var params = _a.params, permissions = _a.permissions, worker = _a.worker, metadata = _a.metadata, config = _a.config, apiPath = _a.apiPath, servicesPath = _a.servicesPath, user = _a.user, workflowPath = _a.workflowPath, entity = _a.entity, tenant = _a.tenant, entityUri = _a.entityUri, query = _a.query, openSearch = _a.openSearch, environment = _a.environment, getCurrentPerspectiveId = _a.getCurrentPerspectiveId, showPerspective = _a.showPerspective, workflowCheckPermission = _a.workflowCheckPermission, setEntityUri = _a.setEntityUri;
    var name = params.name, url = params.url, data = params.data, method = params.method, validationUrl = params.validationUrl;
    var processFromQuery = function () {
        if (!params.processDefinitionId) {
            return new Promise(function (resolve) { return resolve({ errorMessage: 'processDefinitionId is empty' }); });
        }
        if (!params.searchString) {
            return new Promise(function (resolve) { return resolve({ errorMessage: 'searchString is empty' }); });
        }
        if (!workflowPath) {
            return new Promise(function (resolve) { return resolve({ errorMessage: 'Workflow path is not defined' }); });
        }
        var errors = validateParams('/processInstances/_generateFromQuery', permissions);
        if (errors) {
            return new Promise(function (resolve) { return resolve(errors); });
        }
        return startProcessFromQuery({
            workflowPath: workflowPath,
            processType: params.processDefinitionId,
            searchString: params.searchString,
            tenant: tenant,
            environment: environment
        });
    };
    var processInstance = function () {
        if (!params.processDefinitionId) {
            return new Promise(function (resolve) { return resolve({ errorMessage: 'processDefinitionId is empty' }); });
        }
        if (!params.changeRequestURI) {
            return new Promise(function (resolve) { return resolve({ errorMessage: 'changeRequestURI is empty' }); });
        }
        if (!workflowPath) {
            return new Promise(function (resolve) { return resolve({ errorMessage: 'Workflow path is not defined' }); });
        }
        var errors = validateParams('/processInstances', permissions);
        if (errors) {
            return new Promise(function (resolve) { return resolve(errors); });
        }
        return startProcessInstance({
            workflowPath: workflowPath,
            processType: params.processDefinitionId,
            tenant: tenant,
            environment: environment,
            objectURIs: [entityUri, params.changeRequestURI],
            comment: params.comment
        });
    };
    var workflowRequest = function () { return __awaiter(void 0, void 0, void 0, function () {
        var errors, isExternalUrl, headers;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    errors = validateParams(validationUrl, permissions);
                    if (errors) {
                        return [2 /*return*/, errors];
                    }
                    isExternalUrl = url.includes('http:') || url.includes('https:');
                    if (!workflowPath && !isExternalUrl) {
                        return [2 /*return*/, { errorMessage: 'Workflow path is not defined' }];
                    }
                    return [4 /*yield*/, getAuthHeaders(params.headers, servicesPath)];
                case 1:
                    headers = _a.sent();
                    return [4 /*yield*/, sendWorkflowRequest({ url: url, method: method, data: data, tenant: tenant, headers: headers, workflowPath: workflowPath })];
                case 2: return [2 /*return*/, _a.sent()];
            }
        });
    }); };
    var sendApiRequest = function () { return __awaiter(void 0, void 0, void 0, function () {
        var errors, headers;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    errors = validateParams(validationUrl, permissions);
                    if (errors) {
                        return [2 /*return*/, Promise.reject(errors)];
                    }
                    return [4 /*yield*/, getAuthHeaders(params.headers, servicesPath)];
                case 1:
                    headers = _a.sent();
                    return [4 /*yield*/, sendRequestFromCustomSandbox({
                            url: url,
                            method: method,
                            data: data,
                            headers: headers,
                            noRequestProcessor: true,
                            noRetry: true
                        })];
                case 2: return [2 /*return*/, _a.sent()];
            }
        });
    }); };
    var handleRequest = function (request) {
        request
            .then(function (response) { return (response.json ? response.json() : response); })
            .then(function (data) {
            worker.postMessage(__assign({ action: 'response', result: {
                    data: JSON.parse(JSON.stringify(data)),
                    headers: params.headers,
                    status: 200
                } }, params));
        })
            .catch(function (error) {
            worker.postMessage(__assign({ action: 'response', result: {
                    data: JSON.parse(JSON.stringify(error)),
                    headers: params.headers,
                    status: 0
                } }, params));
        });
    };
    switch (name) {
        case RequestAction.API: {
            var request = sendApiRequest();
            handleRequest(request);
            break;
        }
        case RequestAction.WORKFLOW: {
            var request = workflowRequest();
            handleRequest(request);
            break;
        }
        case RequestAction.WORKFLOW_START_PROCESS_FROM_QUERY: {
            var request = processFromQuery();
            handleRequest(request);
            break;
        }
        case RequestAction.WORKFLOW_START_PROCESS_INSTANCE: {
            var request = processInstance();
            handleRequest(request);
            break;
        }
        case RequestAction.GET_CONFIGURATION: {
            worker.postMessage(__assign({ action: 'response', result: metadata }, params));
            break;
        }
        case RequestAction.GET_UI_CONFIGURATION: {
            var response = __assign(__assign({}, config), { action: __assign({}, config.action) });
            if (response.action.permissions) {
                delete response.action.permissions;
            }
            worker.postMessage(__assign({ action: 'response', result: response }, params));
            break;
        }
        case RequestAction.SET_ENTITY_URI: {
            var listener = function (newEntity) {
                return worker.postMessage(__assign({ action: 'response', result: newEntity }, params));
            };
            setEntityUri(params.entityUri, listener);
            break;
        }
        case RequestAction.SET_PERSPECTIVE: {
            showPerspective(params.perspective);
            worker.postMessage(__assign({ action: 'response', result: getCurrentPerspectiveId() }, params));
            break;
        }
        case RequestAction.GET_PERSPECTIVE: {
            if (getCurrentPerspectiveId) {
                worker.postMessage(__assign({ action: 'response', result: getCurrentPerspectiveId() }, params));
            }
            break;
        }
        case RequestAction.WORKFLOW_CHECK_PERMISSION: {
            worker.postMessage(__assign({ action: 'response', result: workflowCheckPermission(params.permission) }, params));
            break;
        }
        case RequestAction.GET_SEARCH_QUERY: {
            worker.postMessage(__assign({ action: 'response', result: query }, params));
            break;
        }
        case RequestAction.OPEN_SEARCH: {
            openSearch({ viewId: config.id, searchState: params.searchState || {} });
            break;
        }
        case RequestAction.GET_ENTITY_URI: {
            worker.postMessage(__assign({ action: 'response', result: entityUri }, params));
            break;
        }
        case RequestAction.GET_ENTITY: {
            worker.postMessage(__assign({ action: 'response', result: entity }, params));
            break;
        }
        case RequestAction.GET_API_PATH: {
            worker.postMessage(__assign({ action: 'response', result: apiPath }, params));
            break;
        }
        case RequestAction.WORKFLOW_GET_WORKFLOW_PATH: {
            worker.postMessage(__assign({ action: 'response', result: workflowPath }, params));
            break;
        }
        case RequestAction.GET_TENANT: {
            worker.postMessage(__assign({ action: 'response', result: tenant }, params));
            break;
        }
        case RequestAction.GET_USER: {
            worker.postMessage(__assign({ action: 'response', result: user }, params));
            break;
        }
        case RequestAction.ALERT: {
            worker.postMessage(__assign({ action: 'response', result: window.alert(params.text) }, params));
            break;
        }
        case RequestAction.CONFIRM: {
            worker.postMessage(__assign({ action: 'response', result: window.confirm(params.text) }, params));
            break;
        }
        case RequestAction.PROMPT: {
            worker.postMessage(__assign({ action: 'response', result: window.prompt(params.text, params.defaultText || '') }, params));
            break;
        }
        case RequestAction.OPEN_WINDOW: {
            window.open(params.url, '_blank');
            break;
        }
        case RequestAction.RELOAD_PAGE: {
            location.reload();
            break;
        }
    }
};
