"use strict";
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());
    });
};
let nRequestId = 1;
const sJsonRPC = "2.0";
const mapURWR = new Map;
const nMaxDelBetweenReqs = 10;
const nMaxTimeReqBlock = 30;
;
;
function UnicSendRecivePostApiWithRetry(sMetod, oParams, nDel = 0, abort) {
    const sKey = JSON.stringify({ metod: sMetod, params: oParams });
    const nCurrTime = GetCurrTime();
    if (mapURWR.has(sKey) && nDel === 0 && (nCurrTime - mapURWR.get(sKey) < nMaxTimeReqBlock * 1000))
        return null;
    if (abort && abort.signal.aborted) {
        mapURWR.delete(sKey);
        return null;
    }
    if (nDel === 0) {
        mapURWR.set(sKey, nCurrTime);
    }
    return new Promise(function (resolve, reject) {
        if (nDel > nMaxDelBetweenReqs) {
            mapURWR.delete(sKey);
            reject();
            return;
        }
        SendRecivePostApi(sMetod, oParams, abort).then(data => {
            const oPAR = data;
            PutPostApiDialogToConsol(oPAR);
            if (oPAR.response.result) {
                mapURWR.delete(sKey);
                resolve(oPAR.response.result);
            }
            else if (oPAR.response.error) {
                if (oPAR.response.error.data && oPAR.response.error.data.error_str == 'must_retry') {
                    nDel = (nDel === 0) ? 1 : nDel * 2;
                    setTimeout(() => {
                        const promise = UnicSendRecivePostApiWithRetry(sMetod, oParams, nDel, abort);
                        if (promise) {
                            promise.then(data => resolve(data)).catch(err => reject(err));
                        }
                        else {
                            reject();
                        }
                    }, nDel * 1000);
                }
                else {
                    mapURWR.delete(sKey);
                    reject({ src: "response error", err: oPAR.response.error });
                }
            }
            else {
                mapURWR.delete(sKey);
                reject({ src: "another response", err: JSON.stringify(oPAR.response) });
            }
        }).catch(err => reject({ src: "request error", err: err }));
    });
}
function SendRecivePostApi(sMetod, oParams, abort) {
    const sRequest = JSON.stringify({ time: GetHmsWithMilliseconds(new Date()), method: sMetod, params: oParams });
    return new Promise(function (resolve, reject) {
        if (!sBearerToken) {
            reject({ title: "SendRecivePostException", message: "There is no Bearer Token", code: 21, name: "NoBearerToken" });
            return;
        }
        nRequestId++;
        if (nRequestId > 2147483647)
            nRequestId = 1;
        let oHeaders = { 'Content-Type': 'application/json' };
        if (sBearerToken) {
            oHeaders.Authorization = " Bearer " + sBearerToken;
        }
        fetch(request_url + "/api", {
            "method": 'POST',
            "mode": 'cors',
            "signal": abort === null || abort === void 0 ? void 0 : abort.signal,
            "headers": oHeaders,
            "body": JSON.stringify({ "jsonrpc": sJsonRPC, "id": nRequestId, "method": sMetod, "params": oParams })
        })
            .then(function (response) {
            if (!response.ok) {
                if (response.status == 401) {
                    sBearerToken = "";
                    localStorage.setItem("sBearerToken", "");
                    sAuthentication = "Str_AuthOldToken";
                }
                reject({ title: "Response is not ok", message: "Error: status: " + response.status + ", statusText: " + response.statusText + ", url: " + response.url });
                return;
            }
            if (abort && abort.signal.aborted) {
                reject({ title: "SendRecivePostException", message: "Fetch was aborted by user", code: 20, name: "AbortError" });
                return;
            }
            let contentType = response.headers.get("Content-Type");
            if (contentType) {
                contentType = contentType.toLowerCase();
            }
            else {
                contentType = "";
            }
            if (contentType.includes("json")) {
                response.json().then((data) => {
                    const oAnsver = { "request": sRequest, "response": data };
                    resolve(oAnsver);
                });
            }
            else if (contentType.includes("text")) {
                response.text().then((text) => {
                    reject({ title: "SendRecivePostErr", message: text, code: -2, name: "Response text/html Err" });
                });
            }
            else {
                const body = response.body;
                if (body && !body.locked) {
                    body.getReader().read().then(xResdData => {
                        const text = xResdData.value ? new TextDecoder().decode(xResdData.value) : GetLocaleText("Err_UnreadableErrorServerAnswer");
                        reject({ title: "SendRecivePostErr", message: text, code: -3, name: "Unreadable Error Server Answer" });
                    });
                }
                else {
                    reject({ title: "SendRecivePostErr", message: GetLocaleText("Err_UnreadableErrorServerAnswer"), code: -3, name: "Unreadable Body Server Answer" });
                }
            }
        })
            .catch((err) => {
            reject({ title: "SendRecivePostErr", message: err.message ? err.message : JSON.stringify(err), code: -3, name: err.name });
        });
    });
}
function SendRecivePostApiCatch(err, sConsoleText, oBDE, oParams) {
    if (oParams) {
        console.log(JSON.stringify(oParams));
        console.log("---------------------------");
    }
    if (err.error) {
        err.title = "";
        err.message = err.error.message;
    }
    console.log(sConsoleText + err.title + ": " + err.message);
    console.log("=============================");
    if (oBDE.Branch && oBDE.DTP && err.name != "AbortError") {
        AddErrorToTree({ message: err.message, data: { error_num: err.code, error_str: "" } }, oBDE);
    }
    else if (oBDE.Branch) {
        const oData = oBDE.Branch.fGetData();
        if (oData && oData.__oAbort__) {
            oData.__oAbort__ = null;
        }
    }
}
function SendRecivePost(command, jsDataForSend, sBody) {
    return new Promise(function (resolve, reject) {
        nRequestId++;
        if (nRequestId > 2147483647)
            nRequestId = 1;
        let body = JSON.stringify(jsDataForSend);
        if (sBody) {
            body = sBody;
        }
        fetch(request_url + command, {
            "method": 'POST',
            "mode": 'cors',
            "headers": { 'Content-Type': 'application/json; charset=utf-8' },
            "body": body
        })
            .then(function (response) {
            if (!response.ok) {
                console.error("Error: status: " + response.status + ", statusText: " + response.statusText + ", url: " + response.url);
                reject("Response not ok. Error: status: " + response.status + ", statusText: " + response.statusText + ", url: " + response.url);
                return;
            }
            response.json().then(function (data) {
                resolve(data);
            }).catch(err => reject("response.jsonErr: " + err));
        })
            .catch(err => reject("SendRecivePostErr: " + err));
    });
}
let nPrevPollingTime = 0;
const nBasePixelRatio = window.devicePixelRatio;
function NewsPolling() {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            if (bDebugMode) {
                const nAntiScale = nBasePixelRatio / window.devicePixelRatio;
                debug_info.style.fontSize = "calc(16px * " + nAntiScale + ")";
                const nCurrT = GetCurrTime();
                const dT = nCurrT - nPrevPollingTime;
                nPrevPollingTime = nCurrT;
                cycle_time.innerHTML = "Cycle time = " + dT / 1000 + " sec";
                if (dT > 1050) {
                    console.log("---------------------------------------------------------------------------");
                    console.log("Cycle time = " + dT / 1000 + " sec. -\"time\":\"" + GetHmsWithMilliseconds(new Date()));
                    console.log("---------------------------------------------------------------------------");
                }
            }
            if (bStopNewsPolling)
                throw null;
            if (!sBearerToken) {
                if (domUserInfo) {
                    domUserInfo.remove();
                    domUserInfo = null;
                }
                Authentication();
                throw null;
            }
            if (pBigSignInDialog) {
                CloseFloatMenu(pBigSignInDialog);
            }
            if (!IsClassElEnable("account_sync_on") && !IsClassElEnable("account_sync_off")) {
                AccountSyncAutoRequest();
            }
            if (!IsClassElEnable("common_auto_on") && !IsClassElEnable("common_auto_off")) {
                GetCommonAutoRun();
            }
            if (aGlobJobArray.length == 0) {
                const aJobStructs = yield JobListWithSmallDataRequest(aJobFieldsForTable);
                if (!aJobStructs)
                    throw null;
                const aIsSchedule = [];
                for (const job of aJobStructs) {
                    let oJobInList = { name: job.opt.sName, __class__: {} };
                    SettingJobShortFields(job.opt, oJobInList);
                    aGlobJobArray.push(oJobInList);
                    if (job.opt.atOnSchedule) {
                        aIsSchedule.push(job.opt.sName);
                    }
                }
                if (aIsSchedule.length > 0) {
                    const aJobSchedule = yield JobListWithSmallDataRequest(aJobFieldsForScedule, aIsSchedule);
                    if (aJobSchedule) {
                        for (const job of aJobSchedule) {
                            const oJobInList = aGlobJobArray.find(item => item.name == job.opt.sName);
                            if (oJobInList && job.opt.schedule) {
                                oJobInList.auto += (oJobInList.auto ? ", " : "") + GetLocaleText("Str_DoOnSchedule") + ": " + ShedItemPrint(job.opt.schedule);
                            }
                        }
                    }
                }
                yield ListGroupRequest();
                JustRefreshAllJobTables(true);
            }
            yield ListJobStatusesRequest();
            yield JobLogRequest();
            oOAuth2.CheckOAuthState();
            if (!domUserInfo) {
                SetUserIdShow();
            }
        }
        catch (_a) { }
        setTimeout(() => __awaiter(this, void 0, void 0, function* () { return yield NewsPolling(); }), 1000);
    });
}
function GetAndShowJobOptions(xArg) {
    return __awaiter(this, void 0, void 0, function* () {
        let sMenuItemForAutoOpening = "";
        let sJobName = sCurrJob;
        const jsOptions = CopyObject(jsFloatMenu.JobOptions);
        if (typeof xArg === 'string') {
            sMenuItemForAutoOpening = xArg;
        }
        else if (xArg && xArg.Branch) {
            sJobName = xArg.Branch.fGetData().name;
            if (!sCurrJob) {
                jsOptions.title = sJobName + " " + GetLocaleText("Str_Options");
            }
        }
        if (sJobName == "")
            return;
        try {
            const oJobData = yield AsyncUnicSendRecivePostApiWithRetry("GetJobByName", { "job_name": sJobName });
            jsCurrJobOptions = oJobData.opt;
            if (!sCurrJob || sCurrJob == oJobData.opt.sName) {
                SetJobOptionMenu(jsOptions, sMenuItemForAutoOpening);
            }
            else {
                yield AsyncHtmlConfirm(GetLocaleText("Qsn_DoYouWantReturnJob", [oJobData.opt.sName, sCurrJob]), "Getting Job Options", eMyConfDefBtn.ok);
                ChangeCurrJob(oJobData.opt.sName, "");
                FillRightWindow();
                SetJobOptionMenu(jsOptions, sMenuItemForAutoOpening);
            }
        }
        catch (oErr) {
            if (oErr && oErr.src && oErr.error.message) {
                ErrorMsgShow("GetJobByName '" + oErr.src + ":", oErr.error.message, "msgbox");
            }
        }
    });
}
function JobOptionsForChangeRequest(oFilter) {
    return __awaiter(this, void 0, void 0, function* () {
        if (Object.keys(oFCO).length == 1 && Object.keys(oFCO.side_coords[0]).length == 0 && Object.keys(oFCO.side_coords[1]).length == 0) {
            return null;
        }
        const sJobName = sCurrJob;
        try {
            const jsJobinfo = yield AsyncUnicSendRecivePostApiWithRetry("GetJobByName", { "job_name": sJobName });
            if (!jsJobinfo || !jsJobinfo.opt) {
                throw "";
            }
            if (oFilter) {
                if (oFilter.Included) {
                    jsJobinfo.opt.Filter.Included = jsJobinfo.opt.Filter.Included.concat(oFilter.Included);
                }
                if (oFilter.Excluded) {
                    jsJobinfo.opt.Filter.Excluded = jsJobinfo.opt.Filter.Excluded.concat(oFilter.Excluded);
                }
            }
            yield SetJobOptions(jsJobinfo.opt);
        }
        catch (catchErr) {
            if (catchErr) {
                if (catchErr.error) {
                    ErrorMsgShow("JobOptionsForChangeRequest " + catchErr.src + ":", catchErr.error.message, "msgbox");
                }
                else if (catchErr.message) {
                    ErrorMsgShow("JobOptionsForChangeRequest (2)", catchErr.message, "msgbox");
                }
            }
        }
    });
}
function CreateTreeItemData(sJobName) {
    const jsShortJobInfo = { name: sJobName, __class__: {} };
    jsShortJobInfo["left_btn_func"] = function () {
        ChangeCurrJob(sJobName, "");
    };
    jsShortJobInfo["fRightBtn"] = function (e) {
        ChangeCurrJob(sJobName, "");
        DeleteAllDropMenu();
        JobContextMenu(jsJobMenu, e.clientX, e.clientY, e.clientX, e.target);
    };
    if (!mapNextTreeChangeIds.has(sJobName)) {
        mapNextTreeChangeIds.set(sJobName, 0);
    }
    return jsShortJobInfo;
}
function PutJobInList(sJobName, nInd) {
    return __awaiter(this, void 0, void 0, function* () {
        aGlobJobArray.splice(nInd, 0, CreateTreeItemData(sJobName));
        try {
            const jsJobinfo = yield AsyncUnicSendRecivePostApiWithRetry("GetJobByName", { "job_name": sJobName });
            SettingJobInListFields(jsJobinfo.opt, jsJobinfo.opt.sName);
            InsertJobToTables();
            MarkNewJobToTables(jsJobinfo.opt.sName);
        }
        catch (oErr) {
            if (oErr && oErr.src && oErr.error.message) {
                ErrorMsgShow("JobByNameProcessing '" + oErr.src + ":", oErr.error.message, "msgbox");
            }
        }
        return aGlobJobArray[nInd];
    });
}
function JobByNameRequest(sJobName) {
    return __awaiter(this, void 0, void 0, function* () {
    });
}
function SettingJobShortFields(jsJobOpt, oJobInList) {
    if (!oJobInList)
        return;
    oJobInList.left_url = jsJobOpt.side_coords[0].conn.sUrlA;
    oJobInList.right_url = jsJobOpt.side_coords[1].conn.sUrlA;
    oJobInList.oSideCoords = jsJobOpt.side_coords;
    oJobInList.nLastRunTime = jsJobOpt.tTimeStamp;
    oJobInList.bHaveAutoOpt = jsJobOpt.atOnFileChange > 0 || jsJobOpt.atOnFolderConnect > 0 || jsJobOpt.atOnStart > 0 ||
        jsJobOpt.atOnTimer > 0 || jsJobOpt.atOnLogout > 0 || jsJobOpt.atOnSchedule > 0;
    oJobInList.direct = GetJobDirect(jsJobOpt.eJobDirection);
    oJobInList.auto = GetJobAutoDescription(jsJobOpt);
}
function SettingJobInListFields(jsJobOpt, sJobName) {
    let oJobInList = aGlobJobArray.find(item => item.name == sJobName);
    SettingJobShortFields(jsJobOpt, oJobInList);
}
function StartJobRequest(sJobName, nCommand) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            yield AsyncUnicSendRecivePostApiWithRetry("StartJob", { "job_name": sJobName, "start_type": nCommand });
            const oJobInList = aGlobJobArray.find(item => item.name == sJobName);
            if (oJobInList) {
                oJobInList["isWaiting"] = nCommand;
            }
        }
        catch (oErr) {
            if (oErr) {
                if (oErr.error.data && oErr.error.data.error_str == 'not_found') {
                    ErrShowInJobTree(oErr.message, sJobName);
                }
                else {
                    ErrorMsgShow("Start Job", oErr.error.message, "msgbox");
                }
            }
        }
    });
}
let oLastLogIds = new Map;
let oLogIdLastRequest = new Map;
function JobLogRequest() {
    return __awaiter(this, void 0, void 0, function* () {
        if (!sCurrJob || !oLastLogIds.has(sCurrJob) || (domRightBottomWindow.style.display == "none"))
            return;
        const sJobName = sCurrJob;
        let nNextLogId = -1;
        if (!oLogIdLastRequest.has(sJobName) || oLogIdLastRequest.get(sJobName) < 0) {
            nNextLogId = 0;
        }
        else if (oLastLogIds.has(sJobName) && (oLastLogIds.get(sJobName) > oLogIdLastRequest.get(sJobName))) {
            nNextLogId = oLogIdLastRequest.get(sJobName);
        }
        else {
            return;
        }
        try {
            const oLogResp = yield AsyncUnicSendRecivePostApiWithRetry("FetchJobLog", { "job_name": sCurrJob, "next_log_id": nNextLogId }, { oMultiPageArrs: { log: [], next_log_id: -1 } });
            oLogIdLastRequest.set(sJobName, oLogResp.next_log_id);
            for (const oLogLine of oLogResp.log) {
                PutLogStrToWindow(oLogLine);
            }
        }
        catch (catchData) {
            if (catchData && catchData.error && catchData.error.message) {
            }
        }
    });
}
const mapNextTreeChangeIds = new Map();
function JobTreeChangesRequest(sJobName) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!sCurrJob || sCurrJob != sJobName || !document.getElementById("job_tree_window")) {
            return;
        }
        try {
            const oJobTreeChanges = yield AsyncUnicSendRecivePostApiWithRetry("ReadJobTreeChanges", { job_name: sJobName, next_change_id: mapNextTreeChangeIds.get(sJobName) });
            const oJobInList = aGlobJobArray.find(item => item.name == sJobName);
            if (!oJobInList)
                return;
            let nOldNextTreeChangeIds = mapNextTreeChangeIds.get(sJobName);
            if (nOldNextTreeChangeIds === undefined) {
                nOldNextTreeChangeIds = -1;
            }
            if (!oJobTreeChanges.changes || !oJobTreeChanges.changes.length) {
                if (oJobInList && (nOldNextTreeChangeIds < oJobTreeChanges.next_change_id)) {
                    oJobInList.bIsGapInJobTreeChanges = true;
                }
                mapNextTreeChangeIds.set(sJobName, oJobTreeChanges.next_change_id);
                return;
            }
            if ((nOldNextTreeChangeIds + oJobTreeChanges.changes.length) < oJobTreeChanges.next_change_id) {
                oJobInList.bIsGapInJobTreeChanges = true;
            }
            if (!jsJobsTables[sJobName] && oJobInList.oJobStatus) {
                mapNextTreeChangeIds.set(sJobName, oJobInList.oJobStatus.next_tree_change_id);
                return;
            }
            mapNextTreeChangeIds.set(sJobName, oJobTreeChanges.next_change_id);
            if (!jsJobsTables[sJobName])
                return;
            let nLastChangedRow = -1, nFirstChangedRow = Number.MAX_VALUE;
            for (const changItem of oJobTreeChanges.changes) {
                if (!changItem.data || !changItem.path)
                    continue;
                let oItem = jsJobsTables[sJobName].fFindBranchStr(changItem.path, "/");
                if (!oItem)
                    continue;
                changItem.name = oItem.pathEl;
                jsJobsTables[sJobName].fSetNewBranchData(changItem, null, oItem);
                if (oItem.dep_ind >= 0 && nLastChangedRow < oItem.dep_ind)
                    nLastChangedRow = oItem.dep_ind;
                if (oItem.dep_ind >= 0 && nFirstChangedRow > oItem.dep_ind)
                    nFirstChangedRow = oItem.dep_ind;
            }
            if (!bFollowTheSync || oJobInList.oJobStatus.job_run_state != "analyze_running" || nLastChangedRow < 0) {
                jsJobsTables[sJobName].ShowRows();
            }
            else if (nLastChangedRow - nFirstChangedRow < jsJobsTables[sJobName].nLines - 1) {
                jsJobsTables[sJobName].ShowRows({ "start": nFirstChangedRow, "finish": nLastChangedRow, "bStartPriority": true });
            }
            else {
                jsJobsTables[sJobName].ShowRows({ "finish": nLastChangedRow });
            }
        }
        catch (_a) { }
    });
}
let nServerDisconnectCycle = 0;
const oOldMyModalPar = { zIndex: "1", display: "none" };
function ListJobStatusesRequest() {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            if (bStopListJobStatusesResponseProcessing)
                return;
            const oJobStatuses = (yield AsyncSendRecivePostApi("ListJobStatuses", {})).response.result;
            if (bStopListJobStatusesResponseProcessing)
                return;
            yield ListJobStatusesResponseProcessing(oJobStatuses);
            if (nServerDisconnectCycle > 0) {
                if (document.getElementById("job_tree_window")) {
                    FillRightWindow();
                }
            }
            nServerDisconnectCycle = 0;
            if (domHtmlErr.style.display != "none") {
                domModal.style.zIndex = oOldMyModalPar.zIndex;
                domModal.style.display = oOldMyModalPar.display;
                oOldMyModalPar.display = "";
            }
            SetDomDisplayAndInnerHtml(domHtmlErr, "none", {});
        }
        catch (catchData) {
            if (!catchData || !catchData.error && !catchData.message) {
                HtmlErrBox("Unknown erro", "Error of Job Statuses Request");
            }
            else {
                let err = catchData.error;
                if (!err) {
                    err = catchData;
                }
                if (err.title == "SendRecivePostErr") {
                    nServerDisconnectCycle++;
                    for (let item of aGlobJobArray) {
                        if (item.isWaiting) {
                            item.isWaiting = JOB_COMMAND_NONE;
                        }
                        if (item.name == sCurrJob) {
                            item.oJobStatus.job_run_state = "not_connected";
                            let pbBox = document.getElementById("main_progress_bar_box");
                            if (pbBox) {
                                pbBox.style.display = "none";
                            }
                            yield ShowTextIfNoTree(item);
                        }
                    }
                    if (err.code < 0) {
                        if (SetDomDisplayAndInnerHtml(domHtmlErr, "flex", { text: "<div>" + err.message + "</div>" })) {
                            if (domModal.style.zIndex != "10000000") {
                                oOldMyModalPar.zIndex = domModal.style.zIndex;
                            }
                            if (domModal.style.display == "none") {
                                oOldMyModalPar.display = "none";
                            }
                            domModal.style.zIndex = "10000000";
                            domModal.style.display = "";
                        }
                    }
                }
            }
        }
    });
}
let bGlobalWaitingBoxFlag = false;
function ListJobStatusesResponseProcessing(jsJobinfo) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!jsJobinfo.job_statuses || !jsJobinfo.job_statuses.length)
            return;
        if (!bExtraJobsDetected && jsJobinfo.job_statuses.length < aGlobJobArray.length) {
            bExtraJobsDetected = true;
            FindExtraJobs(jsJobinfo.job_statuses);
        }
        let bIsDiffers = false;
        let bIsNewJob = false;
        for (let i = 0; i < jsJobinfo.job_statuses.length; i++) {
            const iJS = jsJobinfo.job_statuses[i];
            const sJobName = iJS.sJobName;
            let bNewRunState = false;
            let oJobInList = aGlobJobArray.find(item => item.name == sJobName);
            if (!oJobInList) {
                try {
                    oJobInList = yield PutJobInList(sJobName, i);
                    bIsNewJob = true;
                    bNewRunState = true;
                }
                catch (_a) {
                    continue;
                }
            }
            else {
                if (oJobInList.oJobStatus) {
                    bNewRunState = oJobInList.oJobStatus.job_run_state !== iJS.job_run_state;
                }
            }
            if (oJobInList.stop_go) {
                bNewRunState = true;
            }
            if (!IsJobInListActive(oJobInList)) {
                oJobInList.stop_go = false;
                oJobInList.stop_forsed = false;
            }
            oJobInList.oJobStatus = iJS;
            const oState = oJobInList.oJobStatus.job_run_state;
            let sPrevIcon = oJobInList.job_icon;
            oJobInList.job_icon = GetJobIcon(oJobInList);
            if (sPrevIcon != oJobInList.job_icon) {
                ChangeIconOfGroupJobs(sJobName, oJobInList.job_icon);
                bIsDiffers = true;
            }
            const oStatusData = GetJobStatus(oJobInList.oJobStatus);
            oJobInList.__class__["status"] = oStatusData.class;
            oJobInList.__class__["status_pb_class"] = oStatusData.class;
            oJobInList.status = oStatusData.text;
            oJobInList.nLastRunTime = oJobInList.oJobStatus.last_run_time;
            if (oLogIdLastRequest.get(sJobName) > (iJS.last_log_id + 1)) {
                oLogIdLastRequest.set(sJobName, -1);
            }
            if (mapNextTreeChangeIds.get(sJobName) > iJS.next_tree_change_id) {
                mapNextTreeChangeIds.set(sJobName, 0);
            }
            oLastLogIds.set(sJobName, iJS.last_log_id);
            if (oState == "not_analyzed" && jsJobsTables[sJobName]) {
                jsJobsTables[sJobName].fClear();
            }
            if (oState == "spop_done" && setNeedResetJob.has(sJobName)) {
                ResetJob(sJobName);
            }
            const t1 = GetCurrTime();
            if (sJobName == sCurrJob) {
                const bLastRunTimeIsChanged = oJobInList.tree_tag != iJS.tree_tag;
                oJobInList.tree_tag = iJS.tree_tag;
                if (IsJobHaveAuto(oJobInList)) {
                    DisableClassEl("auto_off");
                    EnableClassEl("auto_on");
                }
                else {
                    EnableClassEl("auto_off");
                    DisableClassEl("auto_on");
                }
                switch (oState) {
                    case "not_analyzed":
                        {
                            EnableClassEl("btn_sync_and_analize");
                            if (IsJobReadyToAnalize(sJobName)) {
                                ActivateClassEl("btn_analize");
                            }
                            else {
                                DeactivateClassEl("btn_analize");
                            }
                            DeactivateClassEl("btn_sync");
                            DisableClassEl("btn_stop_job");
                            if (bNewRunState) {
                                yield ShowTextIfNoTree(oJobInList);
                            }
                            if (jsJobsTables[sJobName]) {
                                jsJobsTables[sJobName].fClear();
                            }
                        }
                        break;
                    case "waiting_for_locks":
                    case "scheduled_to_run":
                        {
                            EnableClassEl("btn_sync_and_analize");
                            DeactivateClassEl("btn_analize");
                            DeactivateClassEl("btn_sync");
                            DisableClassEl("btn_stop_job");
                            yield ShowTextIfNoTree(oJobInList);
                        }
                        break;
                    case "analyze_running":
                        {
                            DeactivateClassEl("btn_sync_and_analize");
                            EnableClassEl("btn_stop_job");
                            if (bNewRunState) {
                                yield ShowTextIfNoTree(oJobInList);
                            }
                            if (oJobInList["isWaiting"] != JOB_COMMAND_NONE || jsJobsTables[sJobName]) {
                                if (jsJobsTables[sJobName]) {
                                    jsJobsTables[sJobName].fClear();
                                    if (jsJobsTables[sJobName].domLimWindow) {
                                        jsJobsTables[sJobName].domLimWindow.innerHTML = "";
                                    }
                                    delete jsJobsTables[sJobName];
                                }
                                oJobInList["isWaiting"] = JOB_COMMAND_NONE;
                            }
                        }
                        break;
                    case "analyze_done":
                        {
                            oJobInList["isWaiting"] = JOB_COMMAND_NONE;
                            EnableClassEl("btn_sync_and_analize");
                            ActivateClassEl("btn_analize");
                            DisableClassEl("btn_stop_job");
                            if (oJobInList.oJobStatus.job_result == RUN_result_ok ||
                                oJobInList.oJobStatus.job_result == RUN_result_nonterm_errors) {
                                ActivateClassEl("btn_sync");
                            }
                            else {
                                DeactivateClassEl("btn_sync");
                            }
                            if (bLastRunTimeIsChanged) {
                                if (jsJobsTables[sJobName] && jsJobsTables[sJobName].fIsNotEmpty()) {
                                    RefreshJobTreeRequest(sJobName);
                                }
                                else {
                                    if (jsJobsTables[sJobName]) {
                                        if (jsJobsTables[sJobName].domLimWindow) {
                                            jsJobsTables[sJobName].domLimWindow.innerHTML = "";
                                        }
                                        delete jsJobsTables[sJobName];
                                    }
                                    JobTreeRequest();
                                    yield ShowTextIfNoTree(oJobInList);
                                }
                            }
                            else if (bNewRunState) {
                                if (!jsJobsTables[sJobName] || !jsJobsTables[sJobName].fIsNotEmpty()) {
                                    JobTreeRequest(sJobName);
                                    yield ShowTextIfNoTree(oJobInList);
                                }
                                else {
                                    ShowTreeIfThisNeeds(sJobName, jsJobsTables[sJobName]);
                                }
                            }
                        }
                        break;
                    case "sync_running":
                    case "sync_done":
                        {
                            ActivateClassEl("btn_analize");
                            DeactivateClassEl("btn_sync");
                            EnableClassEl("btn_sync_and_analize");
                            oJobInList["isWaiting"] = JOB_COMMAND_NONE;
                            if (oState == "sync_running") {
                                EnableClassEl("btn_stop_job");
                                DeactivateClassEl("btn_sync_and_analize");
                            }
                            else {
                                DisableClassEl("btn_stop_job");
                                EnableClassEl("btn_sync_and_analize");
                                if (bNewRunState) {
                                    RefreshJobTreeRequest(sJobName);
                                }
                                if (oJobInList.oJobStatus.job_result == RUN_result_user_stop) {
                                    ActivateClassEl("btn_sync");
                                }
                            }
                            if (bNewRunState || bLastRunTimeIsChanged) {
                                if (!jsJobsTables[sJobName]) {
                                    JobTreeRequest(sJobName);
                                    yield ShowTextIfNoTree(oJobInList);
                                }
                                else {
                                    ShowTreeIfThisNeeds(sJobName, jsJobsTables[sJobName], oJobInList);
                                }
                            }
                            else if (!mapNextTreeChangeIds.has(sJobName) || iJS.next_tree_change_id > mapNextTreeChangeIds.get(sJobName)) {
                                yield JobTreeChangesRequest(sJobName);
                            }
                        }
                        break;
                    case "spop_running":
                        {
                            oJobInList["isWaiting"] = JOB_COMMAND_NONE;
                            DeactivateClassEl("btn_sync_and_analize");
                            EnableClassEl("btn_stop_job");
                            if (pGlobalWaitinBox) {
                                bGlobalWaitingBoxFlag = true;
                                const domPlace = document.getElementById("spop_state_" + pGlobalWaitinBox.id);
                                if (domPlace) {
                                    domPlace.innerText = iJS.sCurrMsg_L + "<p>" + iJS.disk_space_R;
                                }
                            }
                            if (!mapNextTreeChangeIds.has(sJobName) || iJS.next_tree_change_id > mapNextTreeChangeIds.get(sJobName)) {
                                yield JobTreeChangesRequest(sJobName);
                            }
                        }
                        break;
                    case "spop_done":
                        {
                            oJobInList["isWaiting"] = JOB_COMMAND_NONE;
                            EnableClassEl("btn_sync_and_analize");
                            ActivateClassEl("btn_analize");
                            DisableClassEl("btn_stop_job");
                            if (oJobInList.oJobStatus.job_result == RUN_result_ok ||
                                oJobInList.oJobStatus.job_result == RUN_result_nonterm_errors) {
                                ActivateClassEl("btn_sync");
                            }
                            else {
                                DeactivateClassEl("btn_sync");
                            }
                            if (oJobInList.bNeedRefreshAfterSpOp) {
                                delete oJobInList.bNeedRefreshAfterSpOp;
                                RefreshJobTreeRequest(sJobName);
                            }
                            if (oJobInList.pMenu) {
                                if (oJobInList.oJobStatus.job_result == RUN_result_ok) {
                                    HtmlMsgbox(GetLocaleText("Msg_Encr_Test_Empty"), GetLocaleText("Str_Success"));
                                }
                                else {
                                    HtmlMsgbox(GetLocaleText("Err_SmthgWntWrongWthFolderClean"), GetLocaleText("Ttl_ErrMsg"));
                                }
                                delete oJobInList.pMenu;
                            }
                            if (pGlobalWaitinBox && bGlobalWaitingBoxFlag) {
                                CloseFloatMenu(pGlobalWaitinBox);
                                pGlobalWaitinBox = null;
                                bGlobalWaitingBoxFlag = false;
                            }
                            if (!jsJobsTables[sJobName]) {
                                JobTreeRequest(sJobName);
                            }
                            else if (!mapNextTreeChangeIds.has(sJobName) || iJS.next_tree_change_id > mapNextTreeChangeIds.get(sJobName)) {
                                yield JobTreeChangesRequest(sJobName);
                            }
                        }
                        break;
                    case "not_connected":
                        {
                            EnableClassEl("btn_sync_and_analize");
                            DeactivateClassEl("btn_analize");
                            DeactivateClassEl("btn_sync");
                            DisableClassEl("btn_stop_job");
                            if (bNewRunState) {
                                yield ShowTextIfNoTree(oJobInList);
                            }
                        }
                        break;
                }
                let label = document.getElementById("job_status_info");
                if (label)
                    label.innerHTML = oJobInList.status + ', ';
                let detales = document.getElementById("job_status_detale_" + sCurrJob);
                if (detales)
                    detales.innerHTML = GetJobStatusString(oJobInList.oJobStatus);
                let pbb = document.getElementById("main_progress_bar_box");
                if (pbb) {
                    if (oState == "analyze_running" ||
                        oState == "sync_running" ||
                        oState == "spop_running") {
                        pbb.style.display = "";
                        let persent = +oJobInList.oJobStatus.percent_complete;
                        if (isNaN(persent) || persent < 0) {
                            persent = 0;
                        }
                        else if (persent > 100) {
                            persent = 100;
                        }
                        let pb = document.getElementById("progress_bar_" + sCurrJob);
                        if (pb) {
                            pb.style.width = persent + "%";
                        }
                        let domPercent = document.getElementById("sync_analie_percent_num");
                        if (domPercent) {
                            domPercent.innerHTML = persent + "%";
                        }
                    }
                    else {
                        pbb.style.display = "none";
                    }
                }
                if (iJS.disk_space_L && iJS.disk_space_L.total) {
                    SetDiskSpaceInfo(iJS.disk_space_L, "left");
                }
                else {
                    if (domLeftDiagram) {
                        domLeftDiagram.style.display = "none";
                    }
                }
                if (iJS.disk_space_R && iJS.disk_space_R.total) {
                    SetDiskSpaceInfo(iJS.disk_space_R, "right");
                }
                else {
                    if (domRightDiagram) {
                        domRightDiagram.style.display = "none";
                    }
                }
                let domForMsg = document.getElementById("for_left_msg");
                if (domForMsg) {
                    if (iJS.sCurrMsg_L) {
                        domForMsg.style.display = "";
                        domForMsg.innerHTML = iJS.sCurrMsg_L;
                    }
                    else {
                        domForMsg.style.display = "none";
                        domForMsg.innerHTML = "";
                    }
                }
                domForMsg = document.getElementById("for_right_msg");
                if (domForMsg) {
                    if (iJS.sCurrMsg_R) {
                        domForMsg.style.display = "";
                        domForMsg.innerHTML = iJS.sCurrMsg_R;
                    }
                    else {
                        domForMsg.style.display = "none";
                        domForMsg.innerHTML = "";
                    }
                }
            }
            const dT = GetCurrTime() - t1;
            if (bDebugMode) {
                state_processing.innerHTML = "state processing time = " + dT;
            }
        }
        JustRefreshAllJobTables(bIsDiffers || bIsNewJob);
        if (!bLastPrevSessionJobWasOpend) {
            if (!bIsNewJob && pJobListTable && pJobListTable.root.cont && pJobListTable.root.cont.length > 0) {
                bLastPrevSessionJobWasOpend = true;
                let tmp = null;
                if (oWebGuSettings.sCurrJob) {
                    tmp = pJobListTable.MarkTabRow("name", oWebGuSettings.sCurrJob, pJobListTable.root.cont[0]);
                }
                else if (oWebGuSettings.sCurrGroup) {
                    tmp = pJobListTable.MarkTabRow("name", oWebGuSettings.sCurrGroup);
                }
                else if (aGlobJobArray.length > 0) {
                    tmp = pJobListTable.MarkTabRow("name", aGlobJobArray[0].name, pJobListTable.root.cont[0]);
                }
                if (!tmp) {
                    pJobListTable.MarkTabRow("name", aGlobJobArray[0].name, pJobListTable.root.cont[0]);
                }
                if (oWebGuSettings.oJobTableParams.bMoreInfoOpen) {
                    CreateLeftJobTable();
                }
                else {
                    pJobListTable.ShowTable();
                }
            }
        }
    });
}
const READ_JOB_TREE_MAX_ITEM = 1000;
const ALL_JOB_TREE_MAX_ITEM = 5000;
function RefreshJobTreeRequest(sJobName, sPath) {
    if (sJobName != sCurrJob) {
        return;
    }
    let oTableRow = undefined;
    let oOpenFolders = undefined;
    if (!sPath) {
        sPath = "";
        if (jsJobsTables[sJobName]) {
            oOpenFolders = jsJobsTables[sJobName].fGetOpendFolders();
            jsJobsTables[sJobName].fClear();
        }
    }
    else {
        const oDTP = jsJobsTables[sJobName];
        oTableRow = oDTP.fFindBranchStr(sPath, "/");
        if (oTableRow) {
            oTableRow.fClear();
        }
    }
    const oParams = { "job_name": sJobName, "path": sPath, "view_mode": oWebGuSettings.GetTreeMode(sJobName), "max_items": READ_JOB_TREE_MAX_ITEM };
    JobTreeReqAndProc(oParams, oTableRow, oOpenFolders);
}
function OneTreeLineRequest(arr) {
    return __awaiter(this, void 0, void 0, function* () {
        if (arr.length === 0)
            return;
        const sPath = arr[0].path, sFName = arr[0].f_name, bIsLast = arr[0].last_item;
        arr.splice(0, 1);
        try {
            const oParams = { "job_name": sCurrJob, "path": sPath, "view_mode": oWebGuSettings.GetTreeMode(sCurrJob), "start_from": sFName, "max_items": 1 };
            const jsJobTree = yield AsyncUnicSendRecivePostApiWithRetry("ReadJobTree", oParams);
            if (oParams && oParams.job_name && "path" in oParams && "start_from" in oParams && jsJobsTables[oParams.job_name]) {
                let oItem = jsJobsTables[oParams.job_name].fFindBranchStr(oParams.path + "/" + oParams.start_from, "/");
                if (!oItem) {
                    return;
                }
                if (jsJobTree.tree && jsJobTree.tree.length) {
                    jsJobsTables[oParams.job_name].fSetNewBranchData(jsJobTree.tree[0], null, oItem);
                    jsJobsTables[oParams.job_name].ShowRows();
                }
            }
            if (arr.length > 0) {
                OneTreeLineRequest(arr);
            }
            else if (bIsLast) {
                RefreshJobTreeRequest(oParams.job_name, oParams.path + "/" + oParams.start_from);
            }
        }
        catch (oErr) {
        }
    });
}
function SetJobOptions(jsOpt) {
    return __awaiter(this, void 0, void 0, function* () {
        let bWasSideChange = false;
        if (oFCO.side_coords) {
            if (Object.keys(oFCO.side_coords[0]).length > 0) {
                jsOpt.side_coords[0] = oFCO.side_coords[0];
                bWasSideChange = true;
            }
            if (Object.keys(oFCO.side_coords[1]).length > 0) {
                jsOpt.side_coords[1] = oFCO.side_coords[1];
                bWasSideChange = true;
            }
        }
        if (oFCO.eJobDirection !== undefined) {
            jsOpt.eJobDirection = oFCO.eJobDirection;
        }
        for (const key of Object.keys(jsOpt)) {
            if (key.substring(0, 2) == "at") {
                if (jsOpt[key] === true) {
                    jsOpt[key] = 2;
                }
                else if (jsOpt[key] === false) {
                    jsOpt[key] = 0;
                }
            }
        }
        try {
            yield SetJobOptionsRequest(jsOpt);
            if (sCurrJob === jsOpt.sName) {
                FillRightWindow(bWasSideChange);
            }
        }
        catch (oErr) {
            if (sCurrJob === jsOpt.sName) {
                FillRightWindow(bWasSideChange);
            }
            throw oErr;
        }
    });
}
function SetJobOptionsRequest(jsOpt) {
    return __awaiter(this, void 0, void 0, function* () {
        const oJobInList = aGlobJobArray.find(item => item.name == jsOpt.sName);
        let bAutoRunSuspend = true;
        try {
            if (IsJobActive(jsOpt.sName)) {
                yield AsyncHtmlConfirm("Qsn_DoYouWantStopJob", "Cnfrm_SetJobOptions", eMyConfDefBtn.ok);
                if (oJobInList && oJobInList.bHaveAutoOpt) {
                    bAutoRunSuspend = yield GetCommonAutoRun();
                    if (!bAutoRunSuspend) {
                        yield SetCommonAutoRun(true);
                    }
                }
                yield StopRequest(jsOpt.sName, true, true);
            }
            const jsJobinfo = yield AsyncUnicSendRecivePostApiWithRetry("SetJobOptions", { "job_name": jsOpt.sName, "options": jsOpt });
            if (!bAutoRunSuspend) {
                yield SetCommonAutoRun(false);
            }
            if (!jsJobinfo)
                return;
            delete jsJobsTables[jsOpt.sName];
            if (oJobInList && oJobInList.oJobStatus) {
                oJobInList.oJobStatus.job_run_state = "not_analyzed";
            }
            if (!jsJobinfo.new_options) {
                throw "SetJobOptions err: wrong answer";
            }
            SettingJobInListFields(jsJobinfo.new_options, jsOpt.sName);
            FillCurrJobDetalesWindow(true);
        }
        catch (oErr) {
            throw oErr;
        }
    });
}
function JobTreeRequest(sJobName, oTableRow) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!sJobName) {
            sJobName = sCurrJob;
        }
        let oJobInList = aGlobJobArray.find(item => item.name == sJobName);
        if (!oJobInList || !oJobInList.status)
            return;
        if (oTableRow) {
            let sPath = oTableRow.fGetPathStr("/");
            if (oTableRow.cont && oTableRow.cont.length == 0) {
                JobTreeReqAndProc({ "job_name": sJobName, "path": sPath, "view_mode": oWebGuSettings.GetTreeMode(sJobName), "max_items": READ_JOB_TREE_MAX_ITEM }, oTableRow);
            }
        }
        else {
            let window = document.getElementById("job_tree_window");
            if (window) {
                let oJobTable = jsJobsTables[sJobName];
                if (!oJobTable) {
                    JobTreeReqAndProc({ "job_name": sJobName, "path": "", "view_mode": oWebGuSettings.GetTreeMode(sJobName), "max_items": READ_JOB_TREE_MAX_ITEM });
                }
                else {
                    window.innerHTML = "";
                    let inWin = document.createElement("div");
                    inWin.id = "in_win_job_tree_window";
                    window.append(inWin);
                    oJobTable.domContainer = inWin;
                    oJobTable.domLimWindow = window;
                    oJobTable.CreateDomElements();
                }
            }
        }
    });
}
function SetSwitchJobModePanel(oJobInList) {
    if (!oJobInList)
        return;
    if (oJobInList.aTotals) {
        CreatePanelOfJobModeView(oJobInList.aTotals, oWebGuSettings.GetTreeMode(oJobInList.name));
    }
}
function JobTreeReqAndProc(oParams, oTableRow, oOpenFolders) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const oJobTree = yield AsyncUnicSendRecivePostApiWithRetry("ReadJobTree", oParams, { oMultiPageArrs: { tree: [], totals: [], next_name: "" }, nMaxArrLen: 1000 });
            const jsTmpJobTree = oJobTree.tree;
            const oJobInList = aGlobJobArray.find(item => item.name == oParams.job_name);
            if (oJobTree.totals.length > 1 && oJobInList) {
                oJobInList.aTotals = oJobTree.totals;
            }
            let oDTP = jsJobsTables[oParams.job_name];
            if (oDTP) {
                if (jsTmpJobTree.length > 0) {
                    if (oTableRow) {
                        oTableRow.fAddDataArr(jsTmpJobTree, { oDTP, bClean: !oParams.start_from });
                    }
                    else {
                        oDTP.root.fAddDataArr(jsTmpJobTree, { oDTP, bClean: !oParams.start_from });
                    }
                }
            }
            else {
                oDTP = new TDynamicTableProperties();
                oDTP.aHead = jsJobTreeTableHead;
                oDTP.bStriped = true;
                oDTP.bIsTree = true;
                oDTP.fOpenFolder = (oBr) => { JobTreeRequest("", oBr); };
                oDTP.fRightBtn = JobTreeRightButtonFunc;
                oDTP.sPathFieldName = "name";
                oDTP.sSortCol = "name";
                oDTP.fDataProcessor = SetFoldAndClass;
                oDTP.fAutoDeploy = (oBr) => {
                    JobTreeReqAndProc({
                        "job_name": sCurrJob,
                        "path": oBr.fGetPathStr("/"),
                        "view_mode": oWebGuSettings.GetTreeMode(oParams.job_name),
                        "max_items": READ_JOB_TREE_MAX_ITEM
                    }, oBr);
                };
                oDTP.sAutoDeploy = "JobTreeAutoDeploy";
                oDTP.nMinRowHeight = 1.25 + oWebGuSettings.oOpts.eTreeDisplayDensity * 0.25;
                oDTP.root.fAddDataArr(jsTmpJobTree, { oDTP });
                oDTP.fSaveColsSize = (arr) => {
                    for (let i = 0; i < oDTP.aTableColsWidth.length; i++) {
                        if (arr[i] && arr[i] > 0) {
                            oDTP.aTableColsWidth[i] = arr[i];
                        }
                    }
                    if (bJobTreeNarrowMode) {
                        CopyEqSizeArray(oDTP.aTableColsWidth, oWebGuSettings.aJobTreeNarrowTableColsSize);
                    }
                    else {
                        CopyEqSizeArray(oDTP.aTableColsWidth, oWebGuSettings.aJobTreeWideTableColsSize);
                    }
                    localStorage.setItem("oWebGuSettings", JSON.stringify(oWebGuSettings));
                };
                oDTP.fGetColsSizeFromLocStor = () => {
                    if (bJobTreeNarrowMode) {
                        if (oWebGuSettings.aJobTreeNarrowTableColsSize && oWebGuSettings.aJobTreeNarrowTableColsSize.length) {
                            CopyEqSizeArray(oWebGuSettings.aJobTreeNarrowTableColsSize, oDTP.aTableColsWidth);
                            return true;
                        }
                    }
                    else {
                        if (oWebGuSettings.aJobTreeWideTableColsSize && oWebGuSettings.aJobTreeWideTableColsSize.length) {
                            CopyEqSizeArray(oWebGuSettings.aJobTreeWideTableColsSize, oDTP.aTableColsWidth);
                            return true;
                        }
                    }
                    return false;
                };
                jsJobsTables[oParams.job_name] = oDTP;
            }
            if (oTableRow) {
                delete oTableRow.oIsWaiting;
            }
            if (oParams.path === "") {
                SetSwitchJobModePanel(oJobInList);
                if (oJobInList) {
                    oJobInList.bIsGapInJobTreeChanges = false;
                    if (oJobInList.oJobStatus) {
                        mapNextTreeChangeIds.set(oParams.job_name, oJobInList.oJobStatus.next_tree_change_id);
                    }
                }
            }
            if (oDTP && oDTP.fIsNotEmpty()) {
                ShowTreeIfThisNeeds(oParams.job_name, oDTP, oJobInList);
                if (oOpenFolders) {
                    for (const key of Object.keys(oOpenFolders)) {
                        let oNewTableRow;
                        if (oTableRow) {
                            oNewTableRow = oTableRow.fFindEl(key);
                        }
                        else {
                            oNewTableRow = oDTP.root.fFindEl(key);
                        }
                        if (oNewTableRow) {
                            oDTP.ShowTable();
                            yield JobTreeReqAndProc({
                                "job_name": oParams.job_name,
                                "path": oParams.path + "/" + key,
                                "view_mode": oWebGuSettings.GetTreeMode(oParams.job_name),
                                "max_items": READ_JOB_TREE_MAX_ITEM
                            }, oNewTableRow, oOpenFolders[key]);
                        }
                    }
                }
            }
            else {
                yield ShowTextIfNoTree(oJobInList, (oJobInList && oJobInList.oJobStatus && oJobInList.oJobStatus.job_result != RUN_result_term_error));
            }
        }
        catch (oErr) {
            if (oErr.error && oErr.error.data) {
                switch (oErr.error.data.error_str) {
                    case 'not_found':
                        {
                            const oJobTable = jsJobsTables[oParams.job_name];
                            if (!oJobTable) {
                                ErrShowInJobTree(oErr.error.message, oParams.job_name);
                            }
                        }
                        break;
                    case 'bad_page_token':
                        {
                            RefreshJobTreeRequest(oParams.job_name);
                        }
                        break;
                }
            }
        }
    });
}
function SpOpRequestFromJobsList(text, xAddArgs) {
    return __awaiter(this, void 0, void 0, function* () {
        const oSpOpCod = GetSpOp(text);
        if (!oSpOpCod || !oSpOpCod.sp_op) {
            HtmlMsgbox("Command \"" + GetLocaleText(text) + "\" not imolemented ");
            return;
        }
        let sJobName = "";
        if (!xAddArgs) {
            sJobName = sCurrJob;
        }
        else if (!(typeof xAddArgs === 'string')) {
            sJobName = xAddArgs.Branch.fGetData().name;
        }
        else {
            sJobName = xAddArgs;
        }
        let sQuestion = "";
        switch (oSpOpCod.sp_op) {
            case SpOp_DeleteStateFiles:
                {
                    sQuestion = "Str_AskDeleteStates";
                }
                break;
            case SpOp_DeleteRecycledAndHistory:
                {
                    sQuestion = "Str_AskDeleteBackup";
                }
                break;
            case SpOp_DeleteGsData_Both:
                {
                    sQuestion = "Str_AskDeleteGsData";
                }
                break;
        }
        try {
            if (sQuestion) {
                yield AsyncHtmlConfirm(GetLocaleText(sQuestion), "Str_TitleDeleteGsData", eMyConfDefBtn.ok);
            }
            yield AsyncUnicSendRecivePostApiWithRetry("StartSpecOp", { "job_name": sJobName, "spop_type": oSpOpCod.sp_op });
            if (oSpOpCod.sp_op == SpOp_DeleteGsData_Left || oSpOpCod.sp_op == SpOp_DeleteGsData_Right || oSpOpCod.sp_op == SpOp_DeleteGsData_Both) {
                setNeedResetJob.add(sJobName);
            }
        }
        catch (oErr) {
            if (oErr) {
                ErrorMsgShow("StartSpecOp '" + GetLocaleText(text) + "' " + oErr.src + ":", oErr.error.message, "msgbox");
            }
        }
    });
}
function ResetJob(sJobName) {
    return __awaiter(this, void 0, void 0, function* () {
        yield AsyncUnicSendRecivePostApiWithRetry("ResetJob", { "job_name": sJobName });
        setNeedResetJob.delete(sJobName);
        delete jsJobsTables[sJobName];
    });
}
function DeleteGsDataFolderRequest(sJobName, bLeftSide) {
    let text = "Title_JobRightSide";
    let nSpOp = SpOp_DeleteGsData_Right;
    if (bLeftSide) {
        text = "Title_JobLeftSide";
        nSpOp = SpOp_DeleteGsData_Left;
    }
    const promise = UnicSendRecivePostApiWithRetry("StartSpecOp", { "job_name": sJobName, "spop_type": nSpOp });
    if (promise) {
        promise.then(() => { }).catch((oErr) => {
            if (oErr) {
                ErrorMsgShow(GetLocaleText("Str_TitleDeleteGsData") + " " + GetLocaleText(text) + "' " + oErr.src + ":", oErr.error.message, "msgbox");
            }
        });
    }
}
function SpOpRequest(text, oBranchProp) {
    SpOpRequest2(text, oBranchProp.path_arr);
}
function RefreshJobTreeBranch(oBranchProp) {
    RefreshJobTreeRequest(sCurrJob, oBranchProp.path_arr[0]);
}
function SpOpRequest2(text, aItemPaths) {
    const oSpOpCod = GetSpOp(text);
    if (!oSpOpCod) {
        HtmlMsgbox("There is not user act \"" + text + "\" for " + aItemPaths[0]);
        return;
    }
    if (oSpOpCod.sp_op) {
        let aPath = [];
        for (const item of aItemPaths) {
            aPath.push({ "path": "\/" + item, "action": oSpOpCod.user_act });
        }
        SendRecivePostApi("StartSpecOp", { "job_name": sCurrJob, "spop_type": oSpOpCod.sp_op, "paths_actions": aPath }).then(data => SpOpRequestResponseProcessing(data));
    }
    else {
        const oFilters = { Included: [], Excluded: [] };
        for (const item of aItemPaths) {
            if (oSpOpCod.user_act == FLT_ACT_EXC_PATH || oSpOpCod.user_act == FLT_ACT_INC_PATH) {
                SetInExclude("\/" + item, oSpOpCod.user_act, oFilters);
            }
            else {
                SetInExclude(item, oSpOpCod.user_act, oFilters);
            }
        }
        JobOptionsForChangeRequest(oFilters);
    }
}
function SpOpRequestResponseProcessing(jsData) {
    PutPostApiDialogToConsol(jsData);
}
function SimpleSpOpRequest(sJobName, nSpopNumber) {
    SendRecivePostApi("StartSpecOp", { "job_name": sJobName, "spop_type": nSpopNumber }).then(data => SimpleSpOpResponseProcessing(data, sJobName));
}
function SimpleSpOpResponseProcessing(jsData, sJobName) {
    PutPostApiDialogToConsol(jsData);
}
function FileSysWindSettingRequest(domWindow, sUrl, oJobInList, bLeft) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!domWindow || !sUrl)
            return;
        try {
            const ans = yield AsyncUnicSendRecivePostApiWithRetry("ListFileSystems", { "url": sUrl, select: ["$[\"file_systems\"][0][\"icon_url\"]"] });
            if (!ans || ans.file_systems.length !== 1) {
                throw null;
            }
            let sIcon = ans.file_systems[0].icon_url;
            if (sIcon.substring(sIcon.length - 1) == "/") {
                sIcon = "C_Ena_Que_Fil";
            }
            else if (location.pathname != '/web-ui') {
                sIcon = location.pathname + sIcon.replace(/\/web-ui\//, '');
            }
            const img = SetImg(sIcon, "var(--job-detale-img-size)", true);
            domWindow.innerHTML = "";
            if (img) {
                domWindow.append(img);
            }
            if (oJobInList) {
                if (bLeft) {
                    oJobInList.iconFsL = sIcon;
                }
                else {
                    oJobInList.iconFsR = sIcon;
                }
            }
        }
        catch (_a) { }
    });
}
function ListFileSystemsRequest(oIFDD, ind, sUrl2) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const aFs = yield AsyncUnicSendRecivePostApiWithRetry("ListFileSystems");
            BrowseDialogForSideUrlChange(aFs.file_systems, { oIFDD, ind, sUrl2, bWOFiles: true });
        }
        catch (catchErr) {
            SendRecivePostApiCatch(catchErr, "ListFileSystems err: ", {});
        }
    });
}
function AccountByKeyRequest(oSideCoords, eSideNum) {
    const sKey = oSideCoords.sAcctKeyA;
    let oParams;
    oParams = { "start_from": sKey, "max_items": 1 };
    SendRecivePostApi("ListAccounts", oParams)
        .then(data => AccountByKeyResponseProcessing(data, sKey, oSideCoords.sServerDirA, eSideNum, oSideCoords))
        .catch(err => SendRecivePostApiCatch(err, "Accounts '" + sKey + "' err: ", {}));
}
function AccountByKeyResponseProcessing(jsData, sKey, sServerDirA, eSideNum, oFC) {
    PutPostApiDialogToConsol(jsData);
    if (jsData.response.error) {
        return;
    }
    if (jsData.response.result && jsData.response.result.accounts && jsData.response.result.accounts.length > 0) {
        const aBookmarks = jsData.response.result.accounts[0].UnnamedBookmarks;
        const oBMin = aBookmarks.find(it => it.BmkKey == sServerDirA);
        const oBM = new TBookmark;
        if (oBMin) {
            oBM.sServerDirA = oBMin.BmkKey;
            oBM.opts = oBMin.Opts;
        }
        else {
            oBM.sServerDirA = sServerDirA;
        }
        oBM.sAcctKeyA = sKey;
        OpenFolderOptionSets(oBM, jsData.response.result.accounts[0].AcctConn.sUrlA + oBM.sServerDirA, eSideNum, oFC);
    }
}
function SetUnnamedBookmarkRequest(oBM, oBDE) {
    const promise = UnicSendRecivePostApiWithRetry("SetUnnamedBookmark", { "bookmark_data": oBM });
    if (promise) {
        promise.then(respData => {
            if (oBDE && oBDE.Branch && respData.bookmark_data) {
                const oData = oBDE.Branch.fGetData();
                oData.oBookmark = respData.bookmark_data;
                if (oData.icon == "gs-prob-zip") {
                    oData.icon = "gs-zip";
                }
                else {
                    oData.icon = "folder-enc";
                }
                oBDE.Branch.bEncOrZip = true;
                AddBookmarkToAcc(respData.bookmark_data, oBDE.Branch);
                RefreshBrowseBranch("Encrypt", oBDE);
            }
        }).catch(err => SendRecivePostApiCatch(err, "SetUnnamedBookmark '" + oBM.BmkKey + "' err: ", {}));
    }
}
function ListAccForExplorerRequest(oIFDD, oBDE, start_from) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!oBDE.DTP || !oBDE.Branch || oBDE.Branch.oIsWaiting) {
            return;
        }
        if (oBDE.Branch.bError) {
            oBDE.Branch.fClear();
        }
        else if (oIFDD && oBDE.Branch.cont && oBDE.Branch.cont.length > 0) {
            if (oIFDD.conn.sUrlA.endsWith("://") && oBDE.Branch.cont.length > 1) {
                return;
            }
            const oTargetBranch = GetAccWithCreds(oIFDD.conn, oBDE.DTP, oIFDD.user);
            if (oTargetBranch) {
                oBDE.Branch.folder = 1;
                oTargetBranch.folder = 1;
                oBDE.Branch = oTargetBranch;
                FindServerAndFolder(oTargetBranch, oIFDD, oBDE);
                return;
            }
            oBDE.Branch.fClear();
        }
        const oData = oBDE.Branch.fGetData();
        if (!oData.__oAbort__) {
            oData.__oAbort__ = new AbortController();
        }
        ShowWaitingTimer("Getting Accounts list", oBDE);
        const sFsUrl = GetFieldValWithDrillUp(oBDE.Branch, "sFs");
        const oParams = { "fs_url": sFsUrl };
        if (start_from) {
            oParams.start_from = start_from;
        }
        try {
            const oAccList = yield AsyncUnicSendRecivePostApiWithRetry("ListAccounts", oParams, { oMultiPageArrs: { accounts: [], hints: [] }, abort: oData.__oAbort__ });
            if (!oAccList) {
                return;
            }
            const aAccounts = SetBrowsTreeAccounts(oAccList.accounts, oAccList.hints, oBDE.Branch);
            ListAccountsForExplorerResponseProcessing(aAccounts, oIFDD, oBDE);
        }
        catch (oErr) {
            if (oData.__oAbort__.signal.aborted) {
                SendRecivePostApiCatch({ title: "RecivePostException", message: "Fetch was aborted by user (0)", code: -20, name: "AbortError" }, "ListAccounts err (3): ", oBDE);
                return;
            }
            else {
                SendRecivePostApiCatch(oErr, "ListAccounts err: ", oBDE);
            }
        }
    });
}
function FindServerAndFolder(oTargetBranch, oIFDD, oBDE) {
    oBDE.Branch.fMarkAndShow(oBDE.DTP);
    TableRowClick(oBDE.DTP, oBDE.Branch);
    const oData = oTargetBranch.fGetData();
    const url = ParseUrl(oIFDD.conn.sUrlA);
    const sHomePath = oData.sHomePath.startsWith("/") ? oData.sHomePath.slice(1) : oData.sHomePath;
    if (sHomePath) {
        if (url.pathname.startsWith(sHomePath)) {
            url.pathname = url.pathname.slice(sHomePath.length);
            if (url.pathname.startsWith("/")) {
                url.pathname = url.pathname.slice(1);
            }
        }
        else {
            ErrorMsgShow("Error", "Home Path of account (" + sHomePath + ") not in path " + oIFDD.conn.sUrlA, "msgbox");
            return;
        }
    }
    let aJobPath = (url.hostname + "/" + url.pathname).split('/');
    const sFsName = GetFieldValWithDrillUp(oTargetBranch, "sFs");
    if (IsFsGST(sFsName) || oData.bContServList) {
        aJobPath[0] = sFsName + aJobPath[0];
    }
    oBDE.Branch = oTargetBranch;
    if (oData.bContServList) {
        ListServersRequest(oIFDD.conn, aJobPath, oBDE);
    }
    else {
        aJobPath.splice(0, 1);
        ConnectFsRequest(oData.oConn, aJobPath, oBDE, {});
    }
}
function ListAccountsForExplorerResponseProcessing(aAcc, oIFDD, oBDE) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!oBDE.DTP || !oBDE.Branch) {
            return;
        }
        oBDE.Branch.fClear();
        if (!oIFDD) {
            oBDE.Branch.fAddDataArr(aAcc, { fDataProcessor: ProcessAccBranchForTable, sPathFieldName: "sAccKey" });
            oBDE.Branch.folder = 1;
            oBDE.DTP.ShowTable();
            return;
        }
        let oTargetBranch;
        if (oIFDD.key) {
            oTargetBranch = oBDE.Branch.fAddDataArr(aAcc, { fDataProcessor: ProcessAccBranchForTable, sPathFieldName: "sAccKey", sSpecValue: oIFDD.key });
        }
        else {
            oBDE.Branch.fAddDataArr(aAcc, { fDataProcessor: ProcessAccBranchForTable, sPathFieldName: "sAccKey" });
            oTargetBranch = GetAccWithCreds(oIFDD.conn, oBDE.DTP, oIFDD.user);
        }
        oBDE.Branch.folder = 1;
        oBDE.DTP.ShowTable();
        if (oIFDD.conn.sUrlA.endsWith("://")) {
            if (oTargetBranch && oTargetBranch.pathEl == oIFDD.conn.sUrlA) {
                oTargetBranch.fMarkAndShow(oBDE.DTP);
                oBDE.DTP.fGetSelRow(0)._row_.fOpenFolder();
            }
            else if (oBDE.Branch.cont && oBDE.Branch.cont.length === 1) {
                oBDE.Branch.cont[0].fMarkAndShow(oBDE.DTP);
                oBDE.DTP.fGetSelRow(0)._row_.fOpenFolder();
            }
            return;
        }
        if (oTargetBranch) {
            FindServerAndFolder(oTargetBranch, oIFDD, oBDE);
        }
        else if (oBDE.Branch.cont && oBDE.Branch.cont.length === 1) {
            FindServerAndFolder(oBDE.Branch.cont[0], oIFDD, oBDE);
        }
        else {
            AddErrorToTree({ message: "Incorrect or missing account " + oIFDD.key, data: { error_num: -1, error_str: "" } }, oBDE);
        }
    });
}
function ListServersRequest(oConn, aJobPath, oBDE) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!oBDE.Branch || !oBDE.DTP) {
            return;
        }
        if (oBDE.Branch && oBDE.Branch.cont && oBDE.Branch.cont.length > 0) {
            oBDE.Branch.folder = 1;
            if (aJobPath && aJobPath.length > 0) {
                let oServ = oBDE.Branch.fFindEl(aJobPath[0]);
                if (!oServ) {
                    oServ = CreateFakeServer(oConn, aJobPath[0], oBDE);
                }
                if (!oServ) {
                    return;
                }
                aJobPath.splice(0, 1);
                oBDE.Branch = oServ;
                oServ.fMarkAndShow(oBDE.DTP);
                oConn = oServ.fGetData().oConn;
                ConnectFsRequest(oConn, aJobPath, oBDE, {});
            }
            else {
                oBDE.DTP.ShowTable();
            }
            return;
        }
        const oData = oBDE.Branch.fGetData();
        oConn = oData.oConn;
        if (!oData.__oAbort__) {
            oData.__oAbort__ = new AbortController();
        }
        ShowWaitingTimer("Getting Servers list", oBDE);
        try {
            const oServList = yield AsyncUnicSendRecivePostApiWithRetry("ListServers", { "conn": oConn }, { abort: oData.__oAbort__ });
            ListServersResponseProcessing(oServList, aJobPath, oConn, oBDE);
        }
        catch (oErr) {
            if (oErr) {
                if (oErr.error.data.error_str == "needs_custom_gui_auth") {
                    if (!GetFieldValWithDrillUp(oBDE.Branch, "bAuthOauth2")) {
                        try {
                            yield StartTwoFactorAuth(oConn);
                            yield ListServersRequest(oConn, aJobPath, oBDE);
                        }
                        catch (_a) {
                            CleanAndCloseBranch(oBDE);
                        }
                    }
                    else {
                        alert("Auth Oauth2 is necessary");
                    }
                }
                else {
                    SendRecivePostApiCatch({ "message": oErr.error.message, "title": "", "name": oErr.src, "code": oErr.error.data.error_num }, "ListServers err: ", oBDE);
                }
            }
        }
    });
}
function ListServersResponseProcessing(jsData, aJobPath, oConn, oBDE) {
    if (!oBDE.DTP || !oBDE.Branch)
        return;
    if (oBDE.Branch.fGetData().__oAbort__.signal.aborted) {
        SendRecivePostApiCatch({ title: "RecivePostException", message: "Fetch was aborted by user (1)", code: -20, name: "AbortError" }, "ConnectFS err: ", oBDE);
        return;
    }
    oBDE.Branch.fClear();
    let oTargetBranch = SetBrowsTreeServers(jsData.servers, oBDE.Branch, (aJobPath ? aJobPath[0] : undefined), oConn);
    oBDE.Branch.folder = 1;
    oBDE.DTP.ShowTable();
    if (oConn && aJobPath && aJobPath.length > 0) {
        if (!oTargetBranch) {
            oTargetBranch = CreateFakeServer(oConn, aJobPath[0], oBDE);
        }
        if (oTargetBranch) {
            oTargetBranch.fMarkAndShow(oBDE.DTP);
            aJobPath.splice(0, 1);
            oConn.sUrlA = oTargetBranch.fGetData().fGetUrl();
            oBDE.Branch = oTargetBranch;
            ConnectFsRequest(oConn, aJobPath, oBDE, {});
        }
        else {
            HtmlErrBox("Incorrect server name " + aJobPath[0], "Err_BrowseDialog");
        }
    }
}
function CreateFakeServer(oConn, sJobPath, oBDE) {
    const aServers = [{
            "sUrlA": sJobPath,
            "sDisplayNameA": GetServerName(oConn.sUrlA, sJobPath, oConn.sUserIdA),
            "sUserIdA": oConn.sUserIdA,
            "sPasswordEncMasterA": oConn.sPasswordEncMasterA,
            "sCommentA": sJobPath,
            "bHasCheckedIn": false,
            "bDirectOnlyServer": false,
            "tLastSeen": 0
        }];
    const oTargetBranch = SetBrowsTreeServers(aServers, oBDE.Branch, sJobPath, oConn, { display_name: "light_grey_text", comment: "light_grey_text" });
    oBDE.DTP.ShowTable();
    return oTargetBranch;
}
const mapFsReestr = new Map();
function DisconnectOldFs() {
    let nOldestFsTime = -1;
    let nOldestFsKey = "";
    for (let item of mapFsReestr) {
        if (nOldestFsTime < 0) {
            nOldestFsKey = item[0];
            nOldestFsTime = item[1].dt;
        }
        else if (item[1].dt < nOldestFsTime) {
            nOldestFsKey = item[0];
            nOldestFsTime = item[1].dt;
        }
    }
    if (nOldestFsKey) {
        DisconnectFsRequest(nOldestFsKey);
        return true;
    }
    return false;
}
function DisconnectAllFs() {
    for (let item of mapFsReestr.keys()) {
        DisconnectFsRequest(item);
    }
}
function DisconnectFsRequest(filesys_handle) {
    const promise = UnicSendRecivePostApiWithRetry("DisconnectFS", { "filesys_handle": filesys_handle });
    if (promise) {
        promise.then(() => {
            mapFsReestr.delete(filesys_handle);
        }).catch(() => { });
    }
}
function DisconnFromTab(xAddArgs) {
    AsyncUnicSendRecivePostApiWithRetry("DisconnectFS", { "filesys_handle": xAddArgs.Branch.sFsHandle });
}
function ConnectFsRequestPromise(oFC) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            return yield AsyncUnicSendRecivePostApiWithRetry("ConnectFS", { "folder_coords": oFC });
        }
        catch (err) {
            throw err;
        }
    });
}
function ConnectFsRequest(oConn, aJobPath, oBDE, oPar) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!oBDE.DTP || !oBDE.Branch)
            return;
        const oData = oBDE.Branch.fGetData();
        if (oBDE.Branch && oBDE.Branch.cont && oBDE.Branch.cont.length > 0) {
            oBDE.Branch.folder = 1;
            if (aJobPath && aJobPath.length > 0) {
                ListDirForExplorerRequest("", oData.sHomePath ? oData.sHomePath : "", aJobPath, oBDE);
            }
            else {
                oBDE.DTP.ShowTable();
            }
            return;
        }
        if (!oData.__oAbort__) {
            oData.__oAbort__ = new AbortController();
        }
        ShowWaitingTimer("Connecting", oBDE);
        const oFolderCoords = { "conn": oConn, "sAcctKeyA": oData.fGetAccKey() };
        if (oPar.oBM) {
            oFolderCoords.opts = oPar.oBM.opts;
            oFolderCoords.sServerDirA = oPar.oBM.sServerDirA ? oPar.oBM.sServerDirA : oPar.oBM.BmkKey ? oPar.oBM.BmkKey : "";
            oFolderCoords.sBmkNameA = oPar.oBM.BmkKey ? oPar.oBM.BmkKey : oPar.oBM.sServerDirA ? oPar.oBM.sServerDirA : "";
            oFolderCoords.conn = CopyObject(oConn);
            if (IsFsGST(oFolderCoords.conn.sUrlA)) {
                const sServerName = GetGstServerName(oFolderCoords.conn.sUrlA, oFolderCoords.conn.sUserIdA);
                if (sServerName && oPar.oBM.BmkKey.startsWith(sServerName)) {
                    oFolderCoords.conn.sUrlA += oPar.oBM.BmkKey.slice(sServerName.length);
                }
                else {
                    oFolderCoords.conn.sUrlA += oPar.oBM.BmkKey;
                }
            }
            else {
                oFolderCoords.conn.sUrlA += oPar.oBM.BmkKey;
            }
        }
        else if (oData.bIgnoreBookmark && !oData.sFsHandle) {
            oFolderCoords.conn = CopyObject(oConn);
            oFolderCoords.conn.sUrlA += oData.sHomePath;
        }
        try {
            const data = yield AsyncUnicSendRecivePostApiWithRetry("ConnectFS", { "folder_coords": oFolderCoords, "request_free_space": !oPar.oBM, }, { "abort": oData.__oAbort__ });
            ConnectFsResponseProcessing(data, aJobPath, oBDE, oPar);
        }
        catch (oErr) {
            if (oErr) {
                if (oErr.error.data) {
                    try {
                        switch (oErr.error.data.error_str) {
                            case "access_denied":
                                {
                                    if (oPar.bWasAccessDenay) {
                                        const oTmp = { arr: [{ title: "Login: ", value: oConn.sUserIdA }, { title: "Password: ", value: "", password: true }] };
                                        const data = yield CredentialsRequest("Authentication", "Authentication of " + oConn.sUrlA, oTmp);
                                        oConn.sUserIdA = data.arr[0].value;
                                        try {
                                            oConn.sPasswordEncMasterA = yield EncryptStringWithKey(data.arr[1].value, oWebGuSettings.key, oWebGuSettings.iv);
                                            const oBrData = oBDE.Branch.fGetData();
                                            oBrData.comment = oConn.sUserIdA;
                                            oBrData.display_name = GetSummary(oConn);
                                            const oAccPar = { "AcctConn": oConn, "HomePath": oBrData.sHomePath, "Key": oBrData.sAccKey };
                                            CreateAccountRequest(oConn, oBrData.sHomePath, oBDE, { pMenu: null, jsAccData: oAccPar });
                                        }
                                        catch (_a) {
                                            AddErrorToTree({ message: "Authentication failed", data: { error_num: -1, error_str: "Authentication_failed" } }, oBDE);
                                        }
                                    }
                                    else {
                                        const pAcc = GetAccWithCreds(oConn, oBDE.DTP);
                                        if (pAcc) {
                                            CleanAndCloseBranch(oBDE);
                                            if (pAcc.fOpenFolder) {
                                                pAcc.fMarkSelf(oBDE.DTP);
                                                oBDE.DTP.ShowFirstSelectRow();
                                                pAcc.fOpenFolder(pAcc, oBDE.DTP);
                                            }
                                        }
                                        else {
                                            const oTmp = { arr: [{ title: "Login: ", value: "" }, { title: "Password: ", value: "", password: true }] };
                                            const data = yield CredentialsRequest("Authentication", "Authentication of " + oConn.sUrlA, oTmp);
                                            const oTmpConn = CopyObject(oConn);
                                            ;
                                            oTmpConn.sUserIdA = data.arr[0].value;
                                            try {
                                                oTmpConn.sPasswordEncMasterA = yield EncryptStringWithKey(data.arr[1].value, oWebGuSettings.key, oWebGuSettings.iv);
                                                oBDE.Branch.fClear();
                                                oBDE.Branch.folder = 0;
                                                if (oBDE.Branch && oBDE.Branch.pParent && oBDE.Branch.pParent.pParent) {
                                                    oBDE.Branch = oBDE.Branch.pParent.pParent;
                                                    CreateAccountRequest(oTmpConn, "", oBDE, { pMenu: null });
                                                }
                                            }
                                            catch (_b) {
                                                AddErrorToTree({ message: "Authentication failed", data: { error_num: -1, error_str: "Authentication_failed" } }, oBDE);
                                            }
                                        }
                                    }
                                }
                                break;
                            case "needs_custom_gui_auth":
                                {
                                    if (GetFieldValWithDrillUp(oBDE.Branch, "bAuthOauth2")) {
                                        let sUserName = oConn.sDisplayNameA;
                                        if (sUserName && oConn.sUserEmailA) {
                                            sUserName += " (" + oConn.sUserEmailA + ")";
                                        }
                                        else if (oConn.sUserEmailA) {
                                            sUserName = oConn.sUserEmailA;
                                        }
                                        if (!sUserName) {
                                            sUserName = oConn.sUserIdA;
                                        }
                                        yield HtmlConfirm(GetLocaleText("Browse_Str_OAuth2Message", [sUserName], { sQuotes: "'", bBold: true }), GetLocaleText("Browse_Str_OAuth2Interact"), eMyConfDefBtn.ok, { bNoCurrJobName: true });
                                        const oAccData = {
                                            AcctConn: oConn,
                                            HomePath: GetFieldValWithDrillUp(oBDE.Branch, "sHomePath"),
                                            Key: GetFieldValWithDrillUp(oBDE.Branch, "sAccKey"),
                                        };
                                        const menuWait = CreateFloatMenu(jsWaitingBox, { top: "30%", width: "40%" }, { "obj": { oAccData, oBDE } });
                                        menuWait.promise.then(() => { }).catch(() => { });
                                        oOAuth2.SetAuthFormId(menuWait.oMenu.id);
                                        OAuth2ConnectRequest(oConn);
                                    }
                                    else {
                                        yield StartTwoFactorAuth(oConn);
                                        ConnectFsRequest(oConn, aJobPath, oBDE, oPar);
                                    }
                                }
                                break;
                            default: {
                                oBDE.Branch.oTdProperties = {};
                                for (const oTebleCol of oBDE.DTP.aHead) {
                                    oBDE.Branch.oTdProperties[oTebleCol.field_name] = "err_in_light_bg";
                                }
                                AddErrorToTree(oErr.error, oBDE);
                                SetDomDisplayAndInnerHtml(oBDE.domErr, "", { "text": oErr.error.message, class: "job_errors", img: "error" });
                            }
                        }
                    }
                    catch (_c) {
                        CleanAndCloseBranch(oBDE);
                    }
                }
                else {
                    oBDE.Branch.oTdProperties = {};
                    for (const oTebleCol of oBDE.DTP.aHead) {
                        oBDE.Branch.oTdProperties[oTebleCol.field_name] = "err_in_light_bg";
                    }
                    AddErrorToTree(oErr.error, oBDE);
                    SetDomDisplayAndInnerHtml(oBDE.domErr, "", { "text": oErr.error.message, class: "job_errors", img: "error" });
                }
            }
        }
    });
}
function ConnectFsResponseProcessing(jsData, aJobPath, oBDE, oPar) {
    const oData = oBDE.Branch.fGetData();
    if (oData.__oAbort__.signal.aborted) {
        SendRecivePostApiCatch({ title: "RecivePostException", message: "Fetch was aborted by user (2)", code: -20, name: "AbortError" }, "ConnectFS err: ", oBDE);
        return;
    }
    oBDE.Branch.oTdProperties = { display_name: "routine_text", comment: "routine_text" };
    mapFsReestr.set(jsData.filesys_handle, { dt: (new Date()).getTime(), busy: false });
    oData.fSetFsHandle(jsData.filesys_handle, !!oPar.oBM);
    if (jsData.root_free_space_info) {
        const oDiscTotal = ConvertBytes(jsData.root_free_space_info.total);
        const oDiscFree = ConvertBytes(jsData.root_free_space_info.available);
        oData.comment += (oData.comment ? ", " : "") + "Total: " + oDiscTotal.nSpace1 + " " + oDiscTotal.unit + ", Free Space: " + oDiscFree.nSpace1 + " " + oDiscFree.unit;
    }
    if (oData.oBookmarkAcc && !oData.bIgnoreBookmark && !oData.sFsHandle2) {
        oData.sFsHandle2 = oData.sFsHandle;
        oData.oBookmarkAcc.opts = oData.oBookmarkAcc.Opts;
        ConnectFsRequest(oData.oConn, aJobPath, oBDE, { oBM: oData.oBookmarkAcc });
    }
    else {
        ListDirForExplorerRequest(jsData.filesys_handle, oData.oBookmarkAcc ? "" : oPar.sPathForReconnect ? oPar.sPathForReconnect : oData.sHomePath ? oData.sHomePath : "", aJobPath, oBDE, oPar.sFolderName);
    }
    if (!oPar.sPathForReconnect && !oData.oBookmark && !oPar.oBM) {
        FolderCreateInfoRequest(jsData.filesys_handle, (aJobPath === null) ? oBDE : { "Branch": oBDE.Branch, "domErr": oBDE.domErr });
    }
}
const LIST_DIR_MAX_ITEM = 1000;
function ListDirRequestPromise(sFsHandle, sPath, sNextPage, nMaxItems) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!nMaxItems) {
            nMaxItems = LIST_DIR_MAX_ITEM;
        }
        const oParams = { "filesys_handle": sFsHandle, "path": sPath, "max_items": nMaxItems };
        if (sNextPage) {
            oParams.page_token = sNextPage;
        }
        try {
            return yield AsyncUnicSendRecivePostApiWithRetry("ListDir", oParams);
        }
        catch (err) {
            throw err;
        }
    });
}
function ListDirForExplorerRequest(sFsHandle, sPath, aJobPath, oBDE, sNameForMark) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!oBDE.DTP || !oBDE.Branch)
            return;
        if (oBDE.Branch && oBDE.Branch.cont && oBDE.Branch.cont.length > 0 && !oBDE.Branch.oIsWaiting && !oBDE.Branch.bError) {
            oBDE.Branch.folder = 1;
            const oErrBr = oBDE.Branch.cont.find(it => it.bError);
            if (oErrBr) {
                oErrBr.fDeleteSelf();
            }
            oBDE.DTP.ShowTable();
            if (aJobPath && aJobPath.length > 0 && aJobPath[0]) {
                let oNextBranch = oBDE.Branch.fFindEl(aJobPath[0]);
                if (!oNextBranch) {
                    oNextBranch = CreateFakeDir(oBDE, sPath, aJobPath[0]);
                }
                if (oNextBranch) {
                    oNextBranch.fMarkAndShow(oBDE.DTP);
                    const oNextData = oNextBranch.fGetData();
                    if (oNextData.oBookmark && oNextData.sFsHandle && !oNextData.bIgnoreBookmark) {
                        sPath = "";
                        sFsHandle = oNextData.sFsHandle;
                    }
                    else {
                        sPath += "/" + aJobPath[0];
                    }
                    aJobPath.splice(0, 1);
                    oBDE.Branch = oNextBranch;
                    TableRowClick(oBDE.DTP, oNextBranch);
                    if (!oNextBranch.fGetData().bIsFile) {
                        ListDirForExplorerRequest(sFsHandle, sPath, aJobPath, oBDE);
                    }
                }
                else {
                    ErrorMsgShow("", GetLocaleText("Err_SmthgWntWrongWthListDirReq"), "msgbox");
                }
            }
            return;
        }
        const oData = oBDE.Branch.fGetData();
        if (!oData.__oAbort__) {
            oData.__oAbort__ = new AbortController();
        }
        if (!sFsHandle) {
            ShowWaitingTimer("Waiting", oBDE);
            sFsHandle = yield oData.fGetFsHandle(oBDE.Branch, oBDE.Branch, oData.__oAbort__);
        }
        if (oData.__oAbort__.signal.aborted) {
            oData.fGetFsHandle(oBDE.Branch, null);
            oBDE.Branch.fClear();
            return;
        }
        ShowWaitingTimer("Getting Dir list", oBDE);
        const sfPathAndName = oData.oConn.sUrlA + (("sHomePath" in oData) ? oData.sHomePath : ("fGetPathAndName" in oData) ? oData.fGetPathAndName(oBDE.Branch) : "");
        const oBm = GetBookmarkInFolder(sfPathAndName, oBDE.Branch);
        let sTmpPath = sPath;
        if (oBm && !oData.bIgnoreBookmark) {
            if (!oData.sFsHandle2) {
                if (oData.sFsHandle) {
                    if (oBm.bm.opts.nCompressType > 0) {
                        oData.icon = "gs-zip";
                    }
                    else {
                        oData.icon = "folder-enc";
                    }
                    sTmpPath = "";
                }
                else {
                    ConnectFsRequest(oBm.conn, aJobPath, oBDE, { oBM: oBm.bm });
                    return;
                }
            }
            else {
                sTmpPath = "";
            }
        }
        const oParams = { "filesys_handle": sFsHandle, "path": sTmpPath, "max_items": LIST_DIR_MAX_ITEM };
        try {
            const oListDirData = yield AsyncUnicSendRecivePostApiWithRetry("ListDir", oParams, { oMultiPageArrs: { items: [] }, abort: oData.__oAbort__ });
            ListDirForExplorerResponseProcessing(oListDirData.items, sFsHandle, sPath, aJobPath, oBDE, sNameForMark);
        }
        catch (oErr) {
            if (oErr.error && oErr.error.data) {
                switch (oErr.error.data.error_str) {
                    case "bad_page_token":
                        {
                            oBDE.Branch.fClear();
                            ListDirForExplorerRequest(sFsHandle, sPath, aJobPath, oBDE, sNameForMark);
                        }
                        break;
                    case "local_err":
                    case "not_ready":
                        {
                            oBDE.Branch.oTdProperties = {};
                            for (const oTebleCol of oBDE.DTP.aHead) {
                                oBDE.Branch.oTdProperties[oTebleCol.field_name] = "err_in_light_bg";
                            }
                            if ((oBm || oData.sFsHandle2 && oData.oBookmarkAcc) && oData.sFsHandle) {
                                let sBaseFsHandle = "";
                                if (oBm) {
                                    sBaseFsHandle = GetBaseFsHandle(oBDE.Branch);
                                    delete oData.sFsHandle;
                                    oData.bIgnoreBookmark = true;
                                    if (oBm.bm.opts.nCompressType > 0) {
                                        oData.icon = "gs-err-zip";
                                    }
                                    else {
                                        oData.icon = "folder-err-enc";
                                    }
                                }
                                else {
                                    sBaseFsHandle = oData.sFsHandle2;
                                    oData.sFsHandle = oData.sFsHandle2;
                                    delete oData.sFsHandle2;
                                    oData.bIgnoreBookmark = true;
                                    if (oData.oBookmarkAcc.opts.nCompressType > 0) {
                                        oData.icon = "account-err-zip";
                                    }
                                    else {
                                        oData.icon = "account-err-enc";
                                    }
                                }
                                oData.comment = oErr.error.message;
                                ErrorMsgShow("ListDirEncryptOrZipFolder", oErr.error.message, "msgbox");
                                ListDirForExplorerRequest(sBaseFsHandle, oData.fGetPathAndName(oBDE.Branch), aJobPath, oBDE, sNameForMark);
                            }
                            else {
                                AddErrorToTree(oErr.error, oBDE);
                                SetDomDisplayAndInnerHtml(oBDE.domErr, "", { text: oErr.error.message + ": " + sPath, class: "job_errors", img: "error" });
                            }
                        }
                        break;
                    case "disconnected":
                        {
                            ReconnectFs(oBDE);
                        }
                        break;
                    default:
                        oBDE.Branch.oTdProperties = {};
                        for (const oTebleCol of oBDE.DTP.aHead) {
                            oBDE.Branch.oTdProperties[oTebleCol.field_name] = "err_in_light_bg";
                        }
                        AddErrorToTree(oErr.error, oBDE);
                        SetDomDisplayAndInnerHtml(oBDE.domErr, "", { text: oErr.error.message + ": " + sPath, class: "job_errors", img: "error" });
                }
            }
        }
        oData.fGetFsHandle(oBDE.Branch, null);
    });
}
function ListDirForExplorerResponseProcessing(aFolders, sFsHandle, sPath, aJobPath, oBDE, sNameForMark) {
    if (!oBDE.Branch || !oBDE.DTP)
        return;
    oBDE.Branch.fClear();
    const oFolderData = SetBrowsTreeFolders(aFolders, sPath, oBDE.Branch, ["_gsdata_"], !!(oBDE.DTP.fFiltr));
    let oTargetBranch;
    if (aJobPath && aJobPath.length > 0) {
        oTargetBranch = oBDE.Branch.fAddDataArr(oFolderData.aData, {
            oFunc: oFolderData.aFunc,
            fDataProcessor: ProcessFolderBranchForTable,
            "sPathFieldName": "sName",
            "sSpecValue": aJobPath[0],
            "sFieldNameOfSpecValue": "sName"
        });
    }
    else {
        oBDE.Branch.fAddDataArr(oFolderData.aData, { oFunc: oFolderData.aFunc, fDataProcessor: ProcessFolderBranchForTable, "sPathFieldName": "sName" });
    }
    if (!(oBDE.Branch.oTdProperties && oBDE.Branch.oTdProperties.display_name == "err_in_light_bg")) {
        oBDE.Branch.oTdProperties = {};
    }
    oBDE.Branch.folder = 1;
    oBDE.DTP.ShowTable();
    ShowFreeSpace(oBDE.DTP);
    if (sNameForMark) {
        const oEl = oBDE.Branch.fFindEl(sNameForMark);
        if (oEl) {
            oBDE.DTP.MarkTabRow("display_name", sNameForMark, oBDE.Branch);
        }
        else {
            MakeFolderRequest(sFsHandle, sPath + "/" + sNameForMark, oBDE, sNameForMark);
        }
    }
    if (aJobPath === null) {
        return;
    }
    if (!oTargetBranch && aJobPath.length > 0 && aJobPath[0]) {
        oTargetBranch = CreateFakeDir(oBDE, sPath, aJobPath[0]);
    }
    if (oTargetBranch) {
        oTargetBranch.fMarkAndShow(oBDE.DTP);
        TableRowClick(oBDE.DTP, oTargetBranch);
        if (aJobPath.length > 0 && aJobPath[0] && !oTargetBranch.fGetData().bIsFile) {
            sPath += "/" + aJobPath[0];
            aJobPath.splice(0, 1);
            oBDE.Branch = oTargetBranch;
            const oData = oBDE.Branch.fGetData();
            const sfPathAndName = oData.sHomePath ? oData.oConn.sUrlA + oData.sHomePath : oData.oConn.sUrlA + oData.fGetPathAndName(oBDE.Branch);
            const oBm = GetBookmarkInFolder(sfPathAndName, oBDE.Branch);
            if (oBm) {
                ConnectFsRequest(oBm.conn, aJobPath, oBDE, { oBM: oBm.bm });
            }
            else {
                ListDirForExplorerRequest(sFsHandle, sPath, aJobPath, oBDE, sNameForMark);
            }
        }
    }
}
function CreateFakeDir(oBDE, sPath, sJobPath) {
    const oTmpFolder = { bIsFolder: true, sDisplayName: sJobPath, sNameA: sJobPath, size: "0" };
    const oTmpFolderData = SetBrowsTreeFolders([oTmpFolder], sPath, oBDE.Branch, []);
    const oTargetBranch = oBDE.Branch.fAddDataArr(oTmpFolderData.aData, {
        oFunc: oTmpFolderData.aFunc,
        fDataProcessor: ProcessFolderBranchForTable,
        "sPathFieldName": "sName",
        "sSpecValue": sJobPath,
        "sFieldNameOfSpecValue": "sName",
        oTdProperties: { display_name: "light_grey_text", comment: "light_grey_text" }
    });
    oBDE.DTP.ShowTable();
    return oTargetBranch;
}
function ListDirRequestCatch(err, oBDE) {
    if (err.name == "TypeError") {
        err.message = "Disconnect";
    }
    SendRecivePostApiCatch(err, "ListDir err: ", oBDE);
}
function BrowsDialogAccountInfoRequest(oBDE) {
    if (oBDE && oBDE.Branch) {
        const oData = oBDE.Branch.fGetData();
        if (!oData || !oData.sAccKey)
            return;
        SendRecivePostApi("ListAccounts", { "start_from": oData.sAccKey, "max_items": 1 })
            .then(data => BrowsDialogAccountInfoResponseProcessing(data, GetFieldValWithDrillUp(oBDE.Branch, "sFs"), oBDE));
    }
}
function BrowsDialogAccountInfoResponseProcessing(jsData, sFsName, oBDE) {
    PutPostApiDialogToConsol(jsData);
    if (jsData.response.error) {
        switch (jsData.response.error.data.error_str) {
            case "disconnected":
                {
                }
                break;
            case "must_retry":
                {
                }
                break;
        }
        return;
    }
    if (jsData.response.result.accounts && jsData.response.result.accounts.length == 1) {
        ShowAccount(sFsName, jsData.response.result.accounts[0], oBDE);
    }
    else {
        ErrorMsgShow(GetLocaleText("Err_SmthgWntWrong"), "", "msgbox");
    }
}
function BrowsDialogInfoRequest(oBDE) {
    return __awaiter(this, void 0, void 0, function* () {
        if (oBDE && oBDE.Branch) {
            const oData = oBDE.Branch.fGetData();
            try {
                const sFsHandle = yield oData.fGetFsHandle(oBDE.Branch, oBDE.Branch, {});
                if (!sFsHandle) {
                    throw "";
                }
                const sPath = oData.fGetPathAndName(oBDE.Branch);
                const oInfo = yield AsyncUnicSendRecivePostApiWithRetry("GetInfo", { "filesys_handle": sFsHandle, "path": sPath });
                const jsInfo = FolderAndFileInfoProcessing(oInfo.info);
                if (oBDE.Branch.cont && oBDE.Branch.cont.length > 0) {
                    jsInfo.nObjNum = oBDE.Branch.cont.length;
                }
                HtmlMsgbox(JsonToStrAsTree(jsInfo, "<br/>", "", 1, true), "<span style='color:blue'>" + sPath + "</span> info:", { bNoCurrJobName: true });
            }
            catch (oErr) {
                if (oErr) {
                    if (oErr.message) {
                        ErrorMsgShow("GetInfo error:", oErr.message, "msgbox");
                    }
                }
                if (oErr && oErr.data.error_str == "disconnected") {
                    ReconnectFs(oBDE);
                }
                else {
                }
            }
            oData.fGetFsHandle(oBDE.Branch, null);
        }
    });
}
function FolderCreateInfoRequest(sFsHandle, oBDE) {
    const promise = UnicSendRecivePostApiWithRetry("GetInfo", { "filesys_handle": sFsHandle, "path": oBDE.Branch.fGetData().sHomePath });
    if (promise) {
        promise.then(data => FolderCreateInfoResponseProcessing(data, oBDE)).catch(oErr => {
            if (oErr) {
                ErrorMsgShow(oErr.src + ":", oErr.error.message, "msgbox");
            }
        });
    }
}
function FolderCreateInfoResponseProcessing(jsData, oBDE) {
    oBDE.Branch.fGetData().bCanCreateFolders = !(jsData.info.dwAbilities & GS_AB_CANNOT_CREATE_FOLDERS);
    TableRowClick(oBDE.DTP, oBDE.Branch);
}
function DeleteGroupRequest(sGroupName) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            yield AsyncUnicSendRecivePostApiWithRetry("DeleteGroup", { "group_name": sGroupName });
            yield ListGroupRequest("");
            if (pJobListTable) {
                pJobListTable.MarkTabRow("name", sAllJobsGroupName);
            }
        }
        catch (oErr) {
            if (oErr) {
                ErrorMsgShow("DeleteGroup '" + sGroupName + "' " + oErr.src + ":", oErr.error.message, "msgbox");
            }
        }
    });
}
let idGetGroupReq = null;
function AddJobToGroupRequest(sJobName, sGroupName, bDontMarkGroupRightNow) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            yield AsyncUnicSendRecivePostApiWithRetry("AddJobToGroup", { "job_name": sJobName, "group_name": sGroupName });
            if (bDontMarkGroupRightNow) {
                if (idGetGroupReq !== null) {
                    clearTimeout(idGetGroupReq);
                }
                idGetGroupReq = setTimeout(() => __awaiter(this, void 0, void 0, function* () {
                    idGetGroupReq = null;
                    yield ListGroupRequest(sGroupName);
                }), 1000);
            }
            else {
                yield ListGroupRequest(sGroupName);
            }
        }
        catch (oErr) {
            if (oErr && oErr.error && oErr.error.message) {
                ErrorMsgShow("AddJobToGroup '" + sGroupName + "' " + oErr.src + ":", oErr.error.message, "msgbox");
            }
        }
    });
}
function DelJobFromGroupRequest(sJobName, sGroupName) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            yield AsyncUnicSendRecivePostApiWithRetry("RemoveJobFromGroup", { "job_name": sJobName, "group_name": sGroupName });
            yield ListGroupRequest(sGroupName);
        }
        catch (oErr) {
            if (oErr) {
                ErrorMsgShow("RemoveJobFromGroup '" + sGroupName + "' " + oErr.src + ":", oErr.error.message, "msgbox");
            }
        }
    });
}
function DeleteJobRequest(sJobName) {
    sDeletedJob = sJobName;
    SendRecivePostApi("DeleteJob", { "job_name": sJobName }).then(data => {
        DeleteJobResponseProcessing(data, sJobName);
    }).catch((data) => {
        ErrorMsgShow("DeleteJob '" + sJobName + "' catch:", JSON.stringify(data), "both");
    });
}
function DeleteJobResponseProcessing(jsData, sJobName) {
    PutPostApiDialogToConsol(jsData);
    if (jsData.response.error) {
        sDeletedJob = "";
        ErrorMsgShow("DeleteJob '" + sJobName + "' response:", jsData.response.error.message, "both");
    }
    else {
        DeleteJobFromTables([sJobName]);
    }
}
function StopRequest(sJobName, bForse, bWaitRealStop) {
    return __awaiter(this, void 0, void 0, function* () {
        const params = { "job_name": sJobName };
        if (bForse) {
            params.force = true;
        }
        try {
            let oJobInList = aGlobJobArray.find(item => item.name == sJobName);
            if (oJobInList && oJobInList.stop_forsed) {
                return;
            }
            if ((yield AsyncUnicSendRecivePostApiWithRetry("StopJob", params)) === null) {
                return;
            }
            if (oJobInList) {
                if (GetJobIcon(oJobInList) != "stop16") {
                    oJobInList.stop_go = true;
                }
                if (bForse) {
                    oJobInList.stop_forsed = true;
                    while (IsJobActive(sJobName) && bWaitRealStop) {
                        yield new Promise(resolve => setTimeout(resolve, 100));
                    }
                }
            }
        }
        catch (oErr) {
            if (oErr && oErr.src && oErr.error.message && oErr.error.message != "") {
                ErrorMsgShow("StopJob '" + sJobName + "':", oErr.error.message, "msgbox");
            }
        }
    });
}
function CreateAccountRequest(oConn, sHomePath, oBDE, oPar) {
    return __awaiter(this, void 0, void 0, function* () {
        if (oPar.jsAccData) {
            try {
                const data = yield AsyncUnicSendRecivePostApiWithRetry("UpdateAccount", { "account_data": oPar.jsAccData });
                oBDE.Branch.fClear();
                oBDE.Branch.fChangeAllData(data.account_data, SetAccFields);
                RefreshBrowseBranch("", oBDE, oPar.jsAccData.Key);
            }
            catch (oErr) {
                if (oErr && oErr.error && oErr.error.message) {
                    ErrorMsgShow("UpdateAccount response error:", oErr.error.message, "both");
                }
            }
            CloseFloatMenu(oPar.pMenu);
        }
        else {
            try {
                const data = yield AsyncUnicSendRecivePostApiWithRetry("AddNewAccount", { "account_data": { "AcctConn": oConn, "HomePath": sHomePath } });
                CreateAccountResponseProcessing(data, oBDE, oPar.pMenu, true);
            }
            catch (oErr) {
                CloseFloatMenu(oPar.pMenu);
                if (oBDE.DTP) {
                    oBDE.DTP.ShowTable();
                }
                if (oErr && oErr.error && oErr.error.message) {
                    ErrorMsgShow(GetLocaleText("Err_AccountCreationError"), oErr.error.message, "msgbox");
                }
            }
        }
    });
}
function CreateAccountResponseProcessing(jsData, oBDE, pMenu, bFsConn) {
    CloseFloatMenu(pMenu);
    const oBranch = oBDE.Branch;
    jsData.account_data.AcctConn.sUrlA = AddFillUrlForGSTx(jsData.account_data.AcctConn);
    if (oBranch.folder != 1) {
        jsData.account_data.AcctConn.sUrlA += jsData.account_data.HomePath;
        ListAccForExplorerRequest(null, oBDE);
    }
    else {
        const aAccounts = SetBrowsTreeAccounts([jsData.account_data], jsData.account_data.hint.list_servers, oBranch);
        oBranch.fAddDataArr(aAccounts, { fDataProcessor: ProcessAccBranchForTable, sPathFieldName: "sAccKey" });
        oBDE.DTP.ShowTable();
        const oNewBr = oBDE.DTP.MarkTabRow("sAccKey", jsData.account_data.Key, oBranch);
        if (bFsConn && oNewBr && oNewBr.fOpenFolder) {
            oNewBr.fOpenFolder(oNewBr, oBDE.DTP);
        }
    }
}
function DelteAccountRequest(sAccountKey, oBDE) {
    SendRecivePostApi("DeleteAccount", { "Key": sAccountKey })
        .then(data => DeleteAccountResponseProcessing(data, oBDE)).catch(() => { });
}
function DeleteAccountResponseProcessing(jsData, oBDE) {
    PutPostApiDialogToConsol(jsData);
    if ("result" in jsData.response) {
        const ind = oBDE.Branch.indJs;
        const oParent = oBDE.Branch.pParent;
        const aParCont = oParent.cont;
        const i = aParCont.findIndex(it => it.indJs === ind);
        if (i < 0) {
            HtmlMsgbox(GetLocaleText("Err_SmthgWntWrong"));
            return;
        }
        oParent.jsBody.splice(ind, 1);
        aParCont.splice(i, 1);
        aParCont.map(it => { if (it.indJs > ind) {
            it.indJs--;
        } });
        oBDE.DTP.ShowTable();
    }
    else {
        ErrorMsgShow("DeleteAccount response:", jsData.response.error.message, "both", true);
    }
    oBDE.DTP.ResetAllSelects();
    oBDE.DTP.ShowRows();
}
function RenameAccountRequest(sAccountKey, sDisplayName, oBDE) {
    SendRecivePostApi("RenameAccount", { "Key": sAccountKey, "DisplayName": sDisplayName })
        .then(data => RenameAccountResponseProcessing(data, sDisplayName, oBDE)).catch((data) => {
        ErrorMsgShow("RenameAccount catch:", JSON.stringify(data), "both");
    });
}
function RenameAccountResponseProcessing(jsData, sDisplayName, oBDE) {
    PutPostApiDialogToConsol(jsData);
    if ("result" in jsData.response) {
        oBDE.Branch.fSetData("display_name", sDisplayName);
        oBDE.DTP.ShowRows();
    }
    else {
        ErrorMsgShow("RenameAccount response:", jsData.response.error.message, "both", true);
    }
}
function MakeFolderRequest(sFsHandle, sfPathAndName, oBDE, sFolderName) {
    SendRecivePostApi("MakeFolder", { "filesys_handle": sFsHandle, "path": sfPathAndName }).then(data => {
        MakeFolderResponseProcessing(data, oBDE, sFolderName);
    }).catch((data) => {
        ErrorMsgShow("MakeFolder catch:", JSON.stringify(data), "both");
    });
}
function AsyncMakeFolderRequest(sFsHandle, sfPathAndName, oBDE, sFolderName) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const oMakeFolderResp = yield AsyncUnicSendRecivePostApiWithRetry("MakeFolder", { "filesys_handle": sFsHandle, "path": sfPathAndName });
            if (!oBDE.Branch || !oBDE.DTP)
                return;
            if (oBDE.Branch.fIsEmpty()) {
                RefreshBrowseBranch("", oBDE, sFolderName);
            }
            else {
                oMakeFolderResp.info.sNameA = sFolderName;
                const oBTF = SetBrowsTreeFolders([oMakeFolderResp.info], oBDE.Branch.fGetData().fGetPathAndName(oBDE.Branch), oBDE.Branch, []);
                oBDE.Branch.fAddDataArr(oBTF.aData, { oFunc: oBTF.aFunc, fDataProcessor: ProcessFolderBranchForTable, sPathFieldName: "sName" });
                oBDE.Branch.folder = 1;
                oBDE.DTP.ShowTable();
                oBDE.DTP.MarkTabRow("display_name", sFolderName, oBDE.Branch);
            }
        }
        catch (oErr) {
            if (oErr && oErr.error) {
                if (oErr.error.data.error_str == "disconnected") {
                    ReconnectFs(oBDE, sFolderName);
                }
                else {
                    ErrorMsgShow("MakeFolder response:", oErr.error.message, "both");
                }
            }
        }
    });
}
function MakeFolderResponseProcessing(jsData, oBDE, sFolderName) {
    PutPostApiDialogToConsol(jsData);
    if (!oBDE.Branch || !oBDE.DTP)
        return;
    if (jsData.response.error) {
        if (jsData.response.error.data.error_str == "disconnected") {
            ReconnectFs(oBDE, sFolderName);
        }
        else {
            ErrorMsgShow("MakeFolder response:", jsData.response.error.message, "both");
        }
    }
    else {
        if (oBDE.Branch.fIsEmpty()) {
            RefreshBrowseBranch("", oBDE, sFolderName);
        }
        else {
            jsData.response.result.info.sNameA = sFolderName;
            const oBTF = SetBrowsTreeFolders([jsData.response.result.info], oBDE.Branch.fGetData().fGetPathAndName(oBDE.Branch), oBDE.Branch, []);
            oBDE.Branch.fAddDataArr(oBTF.aData, { oFunc: oBTF.aFunc, fDataProcessor: ProcessFolderBranchForTable });
            oBDE.Branch.folder = 1;
            oBDE.DTP.ShowTable();
            oBDE.DTP.MarkTabRow("display_name", sFolderName, oBDE.Branch);
        }
    }
}
function ListGroupRequest(sGroupName) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            aGlobGroup = (yield AsyncUnicSendRecivePostApiWithRetry("ListGroups", {})).groups;
            const nAllJobsInd = aGlobGroup.findIndex(it => it.m_eGroupType == 1);
            if (nAllJobsInd >= 0) {
                sAllJobsGroupName = aGlobGroup[nAllJobsInd].m_sGroupName;
                aGlobGroup.splice(nAllJobsInd, 1);
            }
            if (pJobListTable) {
                const aOpenFolders = pJobListTable.root.fGetOpenBranchFolderArr();
                AddGroupsToTable(aOpenFolders);
                if (sGroupName) {
                    pJobListTable.MarkTabRow("name", sGroupName);
                }
                else if (sGroupName === "") {
                    pJobListTable.fSelTabClean();
                    pJobListTable.ShowRows();
                }
            }
        }
        catch (oErr) {
            if (oErr) {
                ErrorMsgShow("ListGroups " + oErr.src + ":", JSON.stringify(oErr.error), "console");
            }
        }
    });
}
function GetAbout() {
    SendRecivePostApi("GetAboutInfo", {}).then(data => {
        GetAboutResponseProcessing(data);
    }).catch((data) => {
        console.error("ListGroups request fail: " + JSON.stringify(data));
    });
}
function GetAboutResponseProcessing(jsData) {
    PutPostApiDialogToConsol(jsData);
    const oData = jsData.response.result;
    if (!oData) {
        return;
    }
    const jsAbout = { title: oData.product, bottom_box: [{ title: "OK", "close": true, default: true }], cont: [
            { "title": "", cont: [
                    { type: "row", cont: [
                            { type: "column", w: 120, cont: [
                                    { type: "img", title: "", value: "About", w: 100 },
                                ] },
                            { type: "column", w: "30%", cont: [
                                    { type: "text", title: "Version " + oData.version.major + "." + oData.version.minor + "." + oData.version.revision + "." + oData.version.build, class: "about_ver" },
                                    { type: "link", title: oData.website, value: oData.website },
                                    { type: "text", title: "Copyright (C) 1998-2025 Siber Systems Inc." },
                                    { type: "text", title: "License: " + oData.license },
                                    { type: "text", title: "License Platform: " + oData.license_platform },
                                    { type: "text", title: oData.os },
                                ] },
                        ] },
                    { type: "hidden_group", title: "Details", h: 100, cont: [
                            { type: "text", title: oData.details, w_s: "normal" },
                        ] },
                ] }
        ] };
    CreateFloatMenu(jsAbout, { top: "10%", width: "500px" }, null, { bg: "#fff", bNoResize: true }).promise.catch(() => { });
}
function AccountSyncRequest() {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            yield AsyncUnicSendRecivePostApiWithRetry("RequestAccountSync", {});
        }
        catch (oErr) {
            if (oErr && oErr.src && oErr.error.message && oErr.error.message != "") {
                ErrorMsgShow("RequestAccountSync:", oErr.error.message, "msgbox");
            }
        }
    });
}
function AccountSyncAuto(bSet) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            let sConfText = GetLocaleText("Str_ServerAcctJobSync_Ask_Off");
            if (bSet) {
                sConfText = GetLocaleText("Str_ServerAcctJobSync_Ask_On");
            }
            yield AsyncHtmlConfirm(sConfText, "GoodSync", eMyConfDefBtn.ok, { icon: "About", nWidth: 600, bNoCurrJobName: true });
            const oAns = yield AsyncUnicSendRecivePostApiWithRetry("SetAutoAccountSync", { auto_account_sync: bSet });
            bAutoAccSyncOn = oAns.auto_account_sync;
            if (oAns.auto_account_sync) {
                EnableClassEl("account_sync_on");
                DisableClassEl("account_sync_off");
            }
            else {
                EnableClassEl("account_sync_off");
                DisableClassEl("account_sync_on");
            }
        }
        catch (oErr) {
            if (oErr && oErr.src && oErr.error.message && oErr.error.message != "") {
                ErrorMsgShow("RequestAccountSync:", oErr.error.message, "msgbox");
            }
        }
    });
}
function AccountSyncAutoRequest() {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const oAns = yield AsyncUnicSendRecivePostApiWithRetry("GetAutoAccountSync");
            bAutoAccSyncOn = oAns.auto_account_sync;
            if (oAns.auto_account_sync) {
                EnableClassEl("account_sync_on");
                DisableClassEl("account_sync_off");
            }
            else {
                EnableClassEl("account_sync_off");
                DisableClassEl("account_sync_on");
            }
        }
        catch (oErr) {
            if (oErr && oErr.src && oErr.error.message && oErr.error.message != "") {
                ErrorMsgShow("RequestAccountSync:", oErr.error.message, "msgbox");
            }
        }
    });
}
function OpenFileRequest(sFsHandle, sPath) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            return yield AsyncUnicSendRecivePostApiWithRetry("OpenDownload", { "filesys_handle": sFsHandle, "path": sPath });
        }
        catch (err) {
            throw err;
        }
    });
}
function DowloadFleBufRequest(sFsHandle, nBufSize) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            return yield AsyncUnicSendRecivePostApiWithRetry("DownloadBuf", { "filesys_handle": sFsHandle, "size": nBufSize });
        }
        catch (err) {
            throw err;
        }
    });
}
function CloseFileRequest(sFsHandle_1) {
    return __awaiter(this, arguments, void 0, function* (sFsHandle, bCommit = false) {
        try {
            return yield AsyncUnicSendRecivePostApiWithRetry("CloseDownload", { "filesys_handle": sFsHandle, "commit": bCommit });
        }
        catch (_a) { }
    });
}
function AsyncDownloadFile(sFsHandle, sPath) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const oFileOpenData = yield AsyncUnicSendRecivePostApiWithRetry("OpenDownload", { "filesys_handle": sFsHandle, "path": sPath });
            if (!oFileOpenData)
                return null;
            let nPrefSize = Number(oFileOpenData.preferred_buf_size);
            if (isNaN(nPrefSize)) {
                nPrefSize = 0x400000;
            }
            let ui8Out = new Uint8Array(0);
            for (;;) {
                const sBuffContents = yield AsyncUnicSendRecivePostApiWithRetry("DownloadBuf", { "filesys_handle": sFsHandle, "size": nPrefSize });
                if (!sBuffContents || sBuffContents.buf_size === 0)
                    break;
                const ui8New = new Uint8Array(decodeBase64(sBuffContents.buf));
                const ui8Tmp = new Uint8Array(ui8Out.length + ui8New.length);
                ui8Tmp.set(ui8Out, 0);
                ui8Tmp.set(ui8New, ui8Out.length);
                ui8Out = ui8Tmp;
            }
            AsyncUnicSendRecivePostApiWithRetry("CloseDownload", { "filesys_handle": sFsHandle, "commit": false });
            return (new TextDecoder("utf-8")).decode(ui8Out);
        }
        catch (catchData) {
            if (catchData && catchData.error && catchData.error.message) {
                if (!catchData.error.data || catchData.error.data.error_str != "disconnected") {
                    HtmlErrBox(sPath + "</br>" + catchData.error.message, "Error of file download");
                }
            }
            throw catchData;
        }
    });
}
function OAuth2ConnectRequest(oConn) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const jsData = yield AsyncUnicSendRecivePostApiWithRetry("StartOAuth", { conn: oConn });
            if (jsData.consent_url) {
                const ok = openPopup(jsData.consent_url, "windowName: string", 600, 600);
                if (ok) {
                    oOAuth2.SetSessionHandle(jsData.session_handle);
                }
            }
        }
        catch (_a) { }
    });
}
function GetOAuthStateRequest(sSessionHandle) {
    SendRecivePostApi("GetOAuthState", { session_handle: sSessionHandle }).then(data => { GetOAuthStateResponseProcessing(data); }).catch(() => { });
}
function GetOAuthStateResponseProcessing(jsData) {
    PutPostApiDialogToConsol(jsData);
    if (jsData.response.result && (+jsData.response.result.state) > 1) {
        oOAuth2.SetSessionHandle("");
        if (+jsData.response.result.state == 2) {
            const oDialog = oOAuth2.GetDialog();
            if (oDialog && oDialog.jsFloatMenuDescr && oDialog.jsFloatMenuDescr.obj && oDialog.jsFloatMenuDescr.obj.oAccData) {
                const oAccData = oDialog.jsFloatMenuDescr.obj.oAccData;
                oAccData.AcctConn = jsData.response.result.result_conn;
                CreateAccountRequest(jsData.response.result.result_conn, oDialog.jsFloatMenuDescr.obj.oAccData.HomePath, oDialog.jsFloatMenuDescr.obj.oBDE, { jsAccData: oDialog.jsFloatMenuDescr.obj.oAccData, pMenu: oDialog });
            }
            else {
                oOAuth2.SetConnForCreateAccount(jsData.response.result.result_conn);
            }
        }
        else {
            oOAuth2.SetAuthFormId("");
            HtmlErrBox(jsData.response.result.error, GetLocaleText("Err_AuthErr"));
        }
    }
}
class TRetrayRequest {
    constructor(nTL) {
        this.mapDelayedRequests = new Map();
        this.nTimeLimit = nTL * 1000;
    }
    fDeleteSelfByTimeout(sKey) {
        const oReq = this.mapDelayedRequests.get(sKey);
        if (oReq && oReq.timeoutRetray) {
            clearTimeout(oReq.timeoutRetray);
        }
        this.mapDelayedRequests.delete(sKey);
    }
    fAddRequest(sKey, nDelay, bExpBackoff) {
        if (!sKey) {
            return;
        }
        if (!nDelay) {
            nDelay = 1;
        }
        this.mapDelayedRequests.set(sKey, {
            del: nDelay * 1000,
            exp: bExpBackoff,
            timeoutDelete: setTimeout(() => this.fDeleteSelfByTimeout(sKey))
        });
    }
    fDelRequest(sKey) {
        const oReq = this.mapDelayedRequests.get(sKey);
        if (oReq) {
            if (oReq.timeoutRetray) {
                clearTimeout(oReq.timeoutRetray);
            }
            if (oReq.timeoutDelete) {
                clearTimeout(oReq.timeoutDelete);
            }
        }
        this.mapDelayedRequests.delete(sKey);
    }
    fIsRequest(sKey) {
        if (!sKey) {
            return false;
        }
        return !!this.mapDelayedRequests.get(sKey);
    }
    fRetrayRequest(sKey, nDelay, bExpBackoff) {
        if (!sKey) {
            return null;
        }
        if (!nDelay) {
            nDelay = 1;
        }
        const map = this;
        return new Promise(function (resolve, reject) {
            const oKey = JSON.parse(sKey);
            if (oKey) {
                const oReq = map.mapDelayedRequests.get(sKey);
                if (oReq) {
                    if (oReq.exp) {
                        if (oReq.del < map.nTimeLimit / 2) {
                            oReq.del *= 2;
                        }
                    }
                    else if (bExpBackoff) {
                        oReq.exp = true;
                    }
                    if (oReq.timeoutDelete) {
                        clearTimeout(oReq.timeoutDelete);
                    }
                    if (oReq.timeoutRetray) {
                        clearTimeout(oReq.timeoutRetray);
                    }
                    oReq.timeoutDelete = setTimeout(() => map.fDeleteSelfByTimeout(sKey));
                    oReq.timeoutRetray = setTimeout(() => SendRecivePostApi(oKey.metod, oKey.params).then(data => resolve(data)).catch(err => reject(err)), oReq.del);
                }
                else {
                    map.mapDelayedRequests.set(sKey, {
                        del: nDelay * 1000,
                        exp: bExpBackoff,
                        timeoutRetray: setTimeout(() => { SendRecivePostApi(oKey.metod, oKey.params).then(data => resolve(data)).catch(err => reject(err)); }, nDelay * 1000)
                    });
                }
            }
        });
    }
    fClear() {
        this.mapDelayedRequests.clear();
    }
}
let nAnimationCnt = 0;
function WaitingAnimation() {
    let out = document.getElementById("waiting_animation");
    if (!out)
        return;
    SetWaitingSimbols1(out, nAnimationCnt++);
}
function PutPostApiDialogToConsol(data) {
    console.log(data.request);
    console.log("-\"time\":\"" + GetHmsWithMilliseconds(new Date()) + "\"-------------------");
    console.log(JSON.stringify(data.response));
    console.log("=======================================================================================");
}
function ErrorMsgShow(sErrType, sErrMsg, eGoal, bNoCurrJobName) {
    if (eGoal != "msgbox") {
        console.log("error: -\"time\":\"" + GetHmsWithMilliseconds(new Date()) + "\"-------------------");
        console.log(sErrType + ": " + sErrMsg);
        console.log("---------------------------------------------------------------------------");
    }
    if (eGoal != "console") {
        HtmlErrBox(sErrMsg, "Error", { bNoCurrJobName });
    }
}
function LinkToServerOptions() {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const GsServerPreAuth = yield AsyncUnicSendRecivePostApiWithRetry("GetGsServerPreAuth", {});
            window.open(location.protocol + "\/\/" + location.hostname + ":11000" + GsServerPreAuth.preauth_uri, "_blank");
        }
        catch (catchErr) {
            if (catchErr && catchErr.error) {
                ErrorMsgShow("RequestAccountSync " + catchErr.src + ":", catchErr.error.message, "msgbox");
            }
            else {
                ErrorMsgShow("RequestAccountSync unknown error", JSON.stringify(catchErr), "msgbox");
            }
        }
    });
}
function AsyncSendRecivePostApi(sMetod, oParams, abort) {
    return __awaiter(this, void 0, void 0, function* () {
        const sRequest = JSON.stringify({ time: GetHmsWithMilliseconds(new Date()), method: sMetod, params: oParams });
        if (!sBearerToken) {
            throw { title: "SendRecivePostException", message: "There is no Bearer Token", code: 21, name: "NoBearerToken" };
        }
        nRequestId++;
        if (nRequestId > 2147483647)
            nRequestId = 1;
        const oHeaders = { 'Content-Type': 'application/json', Authorization: " Bearer " + sBearerToken };
        try {
            const response = yield fetch(request_url + "/api", {
                method: 'POST',
                mode: 'cors',
                signal: abort === null || abort === void 0 ? void 0 : abort.signal,
                headers: oHeaders,
                body: JSON.stringify({ "jsonrpc": sJsonRPC, "id": nRequestId, "method": sMetod, "params": oParams })
            });
            if (!response.ok) {
                if (response.status === 401) {
                    sBearerToken = "";
                    localStorage.setItem("sBearerToken", "");
                    sAuthentication = "Str_AuthOldToken";
                }
                throw {
                    title: "Response is not ok",
                    message: `Error: status: ${response.status}, statusText: ${response.statusText}, url: ${response.url}`,
                    code: response.status,
                    name: "HttpError"
                };
            }
            if (abort === null || abort === void 0 ? void 0 : abort.signal.aborted) {
                throw { title: "SendRecivePostException", message: "Fetch was aborted by user (after response)", code: 20, name: "AbortError" };
            }
            let contentType = response.headers.get("Content-Type");
            contentType = contentType ? contentType.toLowerCase() : "";
            if (contentType.includes("json")) {
                const data = yield response.json();
                const oAnwver = { "request": sRequest, "response": data };
                return oAnwver;
            }
            else if (contentType.includes("text")) {
                const text = yield response.text();
                throw { title: "SendRecivePostErr", message: text, code: -2, name: "Response text/html Err" };
            }
            else {
                const body = response.body;
                if (body && !body.locked) {
                    try {
                        const reader = body.getReader();
                        const xResdData = yield reader.read();
                        const text = xResdData.value ? new TextDecoder().decode(xResdData.value) : GetLocaleText("Err_UnreadableErrorServerAnswer");
                        throw { title: "SendRecivePostErr", message: text, code: -3, name: "Unreadable Error Server Answer" };
                    }
                    catch (streamError) {
                        console.log("Error reading response stream:", streamError);
                        throw { title: "SendRecivePostErr", message: GetLocaleText("Err_UnreadableErrorServerAnswer"), code: -3, name: "StreamReadError" };
                    }
                }
                else {
                    throw { title: "SendRecivePostErr", message: GetLocaleText("Err_UnreadableErrorServerAnswer"), code: -3, name: "Unreadable Body Server Answer" };
                }
            }
        }
        catch (error) {
            if (error.name === 'AbortError') {
                throw { title: "SendRecivePostException", message: "Fetch was aborted by user", code: 20, name: "AbortError" };
            }
            if (error && typeof error === 'object' && 'title' in error && 'code' in error) {
                throw error;
            }
            throw {
                title: "SendRecivePostErr",
                message: error.message ? error.message : JSON.stringify(error),
                code: -1,
                name: error.name || "NetworkError"
            };
        }
    });
}
function AsyncUnicSendRecivePostApiWithRetry(sMetod_1) {
    return __awaiter(this, arguments, void 0, function* (sMetod, oParams = {}, oSRP = {}) {
        const sKey = JSON.stringify({ metod: sMetod, params: oParams });
        const nCurrTime = Date.now();
        if (!oSRP.nDel) {
            oSRP.nDel = 0;
        }
        if (oSRP.nDel === 0 && mapURWR.has(sKey) && (nCurrTime - mapURWR.get(sKey) < nMaxTimeReqBlock * 1000)) {
            console.log(`Request blocked (duplicate within ${nMaxTimeReqBlock}s): ${sKey}`);
            console.log("----------------------------------------------------------------------");
            return null;
        }
        if (oSRP.abort && oSRP.abort.signal.aborted || oSRP.domMenu && oSRP.domMenu.bSelfDeleted) {
            console.log(`Request aborted by user: ${sKey}`);
            console.log("----------------------------------------------------------------------");
            mapURWR.delete(sKey);
            return null;
        }
        if (oSRP.nDel > nMaxDelBetweenReqs) {
            console.log(`Max retries delay exceeded (${oSRP.nDel} > ${nMaxDelBetweenReqs}) for: ${sKey}`);
            console.log("----------------------------------------------------------------------");
            mapURWR.delete(sKey);
            throw new Error(`Maximum retry delay (${nMaxDelBetweenReqs}s) exceeded for method ${sMetod}`);
        }
        if (oSRP.nDel === 0) {
            mapURWR.set(sKey, nCurrTime);
        }
        try {
            const oPAR = yield AsyncSendRecivePostApi(sMetod, oParams, oSRP.abort);
            PutPostApiDialogToConsol(oPAR);
            if (oPAR.response.result) {
                mapURWR.delete(sKey);
                let bIsArrMaxLen = false;
                if (oSRP.oMultiPageArrs) {
                    for (const sArrName of Object.keys(oSRP.oMultiPageArrs)) {
                        if (Array.isArray(oSRP.oMultiPageArrs[sArrName])) {
                            oSRP.oMultiPageArrs[sArrName] = oSRP.oMultiPageArrs[sArrName].concat(oPAR.response.result[sArrName]);
                            if (oSRP.nMaxArrLen && oSRP.oMultiPageArrs[sArrName].length >= oSRP.nMaxArrLen) {
                                bIsArrMaxLen = true;
                            }
                        }
                        else {
                            oSRP.oMultiPageArrs[sArrName] = oPAR.response.result[sArrName];
                        }
                    }
                    if ((!oParams.max_items || oParams.max_items > 1) && !bIsArrMaxLen) {
                        if (oPAR.response.result.next_account_key) {
                            oParams.start_from = oPAR.response.result.next_account_key;
                            return yield AsyncUnicSendRecivePostApiWithRetry(sMetod, oParams, oSRP);
                        }
                        if (oPAR.response.result.next_page_token) {
                            oParams.page_token = oPAR.response.result.next_page_token;
                            return yield AsyncUnicSendRecivePostApiWithRetry(sMetod, oParams, oSRP);
                        }
                        if (oPAR.response.result.next_name) {
                            oParams.start_from = oPAR.response.result.next_name;
                            return yield AsyncUnicSendRecivePostApiWithRetry(sMetod, oParams, oSRP);
                        }
                    }
                    return oSRP.oMultiPageArrs;
                }
                return oPAR.response.result;
            }
            else if (oPAR.response.error) {
                const oErr = oPAR.response.error;
                if (oErr.data.error_str === 'must_retry') {
                    if (oSRP.break_err_message == oErr.message) {
                        throw oErr;
                    }
                    const nextDelay = (oSRP.nDel === 0) ? 1 : oSRP.nDel * 2;
                    console.log(`Retrying method ${sMetod} for key ${sKey} after ${nextDelay}s delay...`);
                    console.log("----------------------------------------------------------------------");
                    yield new Promise(resolve => setTimeout(resolve, nextDelay * 1000));
                    if (oSRP.abort && oSRP.abort.signal.aborted || oSRP.domMenu && oSRP.domMenu.bSelfDeleted) {
                        console.log(`Request aborted during retry delay: ${sKey}`);
                        console.log("----------------------------------------------------------------------");
                        mapURWR.delete(sKey);
                        throw new Error('Request aborted during retry delay');
                    }
                    oSRP.nDel = nextDelay;
                    return yield AsyncUnicSendRecivePostApiWithRetry(sMetod, oParams, oSRP);
                }
                else {
                    mapURWR.delete(sKey);
                    throw { src: "response error", error: oErr, extData: sKey };
                }
            }
            else {
                mapURWR.delete(sKey);
                const oErr = { message: JSON.stringify(oPAR.response), code: -2, data: { error_num: -2, error_str: "another_post_response_error" } };
                throw { src: "another response", error: oErr };
            }
        }
        catch (error) {
            mapURWR.delete(sKey);
            if (oSRP.abort && oSRP.abort.signal.aborted || oSRP.domMenu && oSRP.domMenu.bSelfDeleted) {
                console.log(`Request aborted during operation: ${sKey}`);
                mapURWR.delete(sKey);
                const oErr = { message: 'Request aborted', code: -3, data: { error_num: -3, error_str: "request_aborted" } };
                throw { src: "another response", error: oErr };
            }
            if (error && typeof error === 'object' && 'src' in error) {
                throw error;
            }
            else {
                throw { src: "request error or internal", error };
            }
        }
    });
}
function trueStreamingDownloadToDisk(url, suggestedName) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const fileHandle = yield window.showSaveFilePicker({ suggestedName });
            const writableStream = yield fileHandle.createWritable();
            const oJobServerAboutInfoResult = yield AsyncUnicSendRecivePostApiWithRetry("GetAboutInfo", {});
            const response = yield fetch(url);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            if (!response.body) {
                throw new Error('Response body is null');
            }
            yield response.body.pipeTo(writableStream);
            console.log('File downloaded and saved successfully!');
        }
        catch (error) {
            if (error.name === 'AbortError') {
                console.log('File save dialog aborted by the user.');
            }
            else {
                console.log('Error during download or save:', error);
            }
        }
    });
}
