"use strict";
let nRequestId = 1;
const sJsonRPC = "2.0";
const DEF_DEL_BETWEEN_REQS = 20;
let nMaxDelBetweenReqs = DEF_DEL_BETWEEN_REQS;
const mapURWR = new Map;
;
;
async function SendRecivePostApiWithRetry(sMetod, oParams = {}, oSRP = {}) {
    const sKey = JSON.stringify({ metod: sMetod, params: oParams });
    const nCurrTime = Date.now();
    if (!oSRP.nDel) {
        oSRP.nDel = 0;
    }
    if (oSRP.abort && oSRP.abort.signal.aborted || oSRP.domMenu && oSRP.domMenu.bSelfDeleted) {
        console.log(`Request aborted by user: ${sKey}`);
        console.log("----------------------------------------------------------------------");
        mapURWR.delete(sKey);
        throw null;
    }
    if (oSRP.nDel > nMaxDelBetweenReqs) {
        console.log(`Max retries delay exceeded (${oSRP.nDel} > ${nMaxDelBetweenReqs}) for: ${sKey}`);
        console.log("----------------------------------------------------------------------");
        try {
            await AsyncHtmlConfirm(GetLocaleText("Ask_TooMuchRetryed", [sMetod]), "Title_TooMuchRetryed", eMyConfDefBtn.ok, { ok: "Btn_Wait", cancel: "Btn_Abort", bNoCurrJobName: true, icon: "C_Ena_Que_Fil" });
            oSRP.nDel = 1;
            nMaxDelBetweenReqs *= 2;
        }
        catch {
            nMaxDelBetweenReqs = DEF_DEL_BETWEEN_REQS;
            console.log(`Request aborted by user: ${sKey}`);
            console.log("----------------------------------------------------------------------");
            mapURWR.delete(sKey);
            throw null;
        }
    }
    if (oSRP.nDel === 0) {
        mapURWR.set(sKey, nCurrTime);
    }
    try {
        const oPAR = await AsyncSendRecivePostApi(sMetod, oParams, (oSRP.abort) ? oSRP.abort.signal : undefined);
        PutPostApiDialogToConsol(oPAR);
        if (oPAR.response.result) {
            mapURWR.delete(sKey);
            nMaxDelBetweenReqs = DEF_DEL_BETWEEN_REQS;
            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 await SendRecivePostApiWithRetry(sMetod, oParams, oSRP);
                    }
                    if (oPAR.response.result.next_page_token) {
                        oParams.page_token = oPAR.response.result.next_page_token;
                        return await SendRecivePostApiWithRetry(sMetod, oParams, oSRP);
                    }
                    if (oPAR.response.result.next_name) {
                        oParams.start_from = oPAR.response.result.next_name;
                        return await SendRecivePostApiWithRetry(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 || oSRP.bDontRetry) {
                    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("----------------------------------------------------------------------");
                await 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 await SendRecivePostApiWithRetry(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);
            throw null;
        }
        if (error && typeof error === 'object' && 'src' in error) {
            throw error;
        }
        else {
            throw { src: "request error or internal", error };
        }
    }
}
async function AsyncSendRecivePostApi(sMetod, oParams, abortSignal) {
    const sRequest = JSON.stringify({ time: GetHmsWithMilliseconds(new Date()), method: sMetod, params: oParams });
    if (!sBearerToken && !bItIsJobExplorer) {
        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 = await fetch(request_url + "/api", {
            method: 'POST',
            mode: 'cors',
            signal: abortSignal,
            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 (abortSignal && abortSignal.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 = await response.json();
            const oAnwver = { "request": sRequest, "response": data };
            return oAnwver;
        }
        else if (contentType.includes("text")) {
            const text = await 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 = await 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) {
            if (error.message && error.message.startsWith("<!doctype html>")) {
                ErrorMsgShow(error.message, { eGoal: "both", bNoCurrJobName: true });
            }
            else {
                throw error;
            }
        }
        throw {
            title: "SendRecivePostErr",
            message: error.message ? error.message : JSON.stringify(error),
            code: -1,
            name: error.name || "NetworkError"
        };
    }
}
function SendRecivePostApiCatch(err, sConsoleText, oBDE, oParams) {
    if (oParams) {
        console.log(JSON.stringify(oParams));
        console.log("---------------------------");
    }
    if (!err) {
        return;
    }
    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;
async function NewsPolling() {
    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 > 1100) {
                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 (glob.IsNotJobArr()) {
            const aJobStructs = await JobListWithSmallDataRequest(aJobFieldsForTable);
            if (!aJobStructs)
                throw null;
            const aIsSchedule = [];
            oSavedData.ClearJobArrBySide();
            for (const job of aJobStructs) {
                let oJobInList = { name: job.opt.sName, __class__: {} };
                SettingJobShortFields(job.opt, oJobInList);
                glob.PushJob(oJobInList);
                if (job.opt.atOnSchedule) {
                    aIsSchedule.push(job.opt.sName);
                }
                oSavedData.SaveJobSides(job.opt);
            }
            localStorage.setItem("oSavedData", JSON.stringify(oSavedData));
            if (aIsSchedule.length > 0) {
                const aJobSchedule = await JobListWithSmallDataRequest(aJobFieldsForScedule, aIsSchedule);
                if (aJobSchedule) {
                    for (const job of aJobSchedule) {
                        const oJobInList = glob.GetJobInList(job.opt.sName);
                        if (oJobInList && job.opt.schedule) {
                            oJobInList.auto += (oJobInList.auto ? ", " : "") + GetLocaleText("Str_DoOnSchedule") + ": " + ShedItemPrint(job.opt.schedule);
                        }
                    }
                }
            }
            await ListGroupRequest();
            glob.JustRefreshAllJobTables(true);
            if (oSavedData.oJobTableParams.bMoreInfoOpen) {
                LeftJobTableCreating(true);
            }
            else {
                glob.ShowMainJobTree();
            }
        }
        await ListJobStatusesRequest();
        await JobLogRequest();
        if (!domUserInfo) {
            SetUserIdShow();
        }
    }
    catch { }
    setTimeout(async () => await NewsPolling(), 1000);
}
async function JobOptionsForChangeRequest(oFCO, bClearAuto, oFilter) {
    if (Object.keys(oFCO).length == 1 && Object.keys(oFCO.side_coords[0]).length == 0 && Object.keys(oFCO.side_coords[1]).length == 0 && !oFilter) {
        return null;
    }
    const sJobName = sCurrJob;
    try {
        const jsJobinfo = await SendRecivePostApiWithRetry("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);
            }
        }
        if (bClearAuto) {
            jsJobinfo.opt.atOnFileChange = 0;
            jsJobinfo.opt.atOnFolderConnect = 0;
            jsJobinfo.opt.atOnStart = 0;
            jsJobinfo.opt.atOnTimer = 0;
            jsJobinfo.opt.atOnLogout = 0;
            jsJobinfo.opt.atOnSchedule = 0;
        }
        await SetJobOptions(jsJobinfo.opt, oFCO);
    }
    catch (catchErr) {
        if (catchErr) {
            if (catchErr.error) {
                ErrorMsgShow(catchErr.error.message);
            }
            else if (catchErr.message) {
                ErrorMsgShow(catchErr.message);
            }
        }
    }
}
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 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);
}
async function StartJobRequest(sJobName, nCommand) {
    try {
        const oParams = { "job_name": sJobName, "start_type": nCommand };
        const oJobInList = glob.GetJobInList(sJobName);
        if (oJobInList) {
            if (oJobInList.bOverrideByLocks) {
                oParams.override_locks = true;
                delete oJobInList.bOverrideByLocks;
            }
            else if (oJobInList.bOverrideByBadState) {
                oParams.override_bad_state_file = true;
                delete oJobInList.bOverrideByBadState;
            }
        }
        await SendRecivePostApiWithRetry("StartJob", oParams);
        if (oJobInList) {
            oJobInList["isWaiting"] = nCommand;
        }
    }
    catch (oErr) {
        CatchErrProcess(oErr, "StartJob");
    }
}
let oLastLogIds = new Map;
let oLogIdLastRequest = new Map;
async function JobLogRequest() {
    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 = await SendRecivePostApiWithRetry("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();
let dtLastTreeChangeRecuest = GetCurrTime();
async function JobTreeChangesRequest(sJobName) {
    dtLastTreeChangeRecuest = GetCurrTime();
    if (!sCurrJob || sCurrJob != sJobName || !document.getElementById("job_tree_window")) {
        return;
    }
    try {
        const oJobTreeChanges = await SendRecivePostApiWithRetry("ReadJobTreeChanges", { job_name: sJobName, next_change_id: mapNextTreeChangeIds.get(sJobName), max_items: 1000 });
        const oJobInList = glob.GetJobInList(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);
            if (!oJobTreeChanges.active_paths || !oJobTreeChanges.active_paths.length)
                return;
        }
        if ((nOldNextTreeChangeIds + oJobTreeChanges.changes.length) < oJobTreeChanges.next_change_id) {
            oJobInList.bIsGapInJobTreeChanges = true;
        }
        const oDTP = jsJobsTables[sJobName];
        if (!oDTP && oJobInList.oJobStatus) {
            mapNextTreeChangeIds.set(sJobName, oJobInList.oJobStatus.next_tree_change_id);
            return;
        }
        mapNextTreeChangeIds.set(sJobName, oJobTreeChanges.next_change_id);
        if (!oDTP)
            return;
        let nLastChangedRow = -1, nFirstChangedRow = Number.MAX_VALUE;
        for (const changItem of oJobTreeChanges.changes) {
            if (!changItem.data || !changItem.path)
                continue;
            const aPath = changItem.path.split("/");
            if (aPath[0] === "") {
                aPath.splice(0, 1);
            }
            await oDTP.fAutoDeployBranch(aPath, oDTP.root.cont[0]);
            let oItem = oDTP.fFindBranchArr(aPath, oDTP.root.cont[0]);
            if (!oItem)
                continue;
            changItem.name = oItem.pathEl;
            oDTP.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;
        }
        for (const changItem of oJobTreeChanges.active_paths) {
            const aPath = changItem.path.split("/");
            if (aPath[0] === "") {
                aPath.splice(0, 1);
            }
            await oDTP.fAutoDeployBranch(aPath, oDTP.root.cont[0]);
            let oItem = oDTP.fFindBranchArr(aPath, oDTP.root.cont[0]);
            if (!oItem)
                continue;
            changItem.name = oItem.pathEl;
            oDTP.fSetNewBranchData(changItem, SetPercentOfSync, 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 (oJobInList.oJobStatus.job_run_state != "sync_running" || nLastChangedRow < 0) {
            oDTP.ShowTable();
        }
        else if (nLastChangedRow - nFirstChangedRow < oDTP.nLines - 1) {
            oDTP.ShowTable({ "start": nFirstChangedRow, "finish": nLastChangedRow, "bStartPriority": true });
        }
        else {
            oDTP.ShowTable({ "finish": nLastChangedRow });
        }
    }
    catch { }
}
let nServerDisconnectCycle = 0;
const oOldMyModalPar = { zIndex: "1", display: "none" };
async function ListJobStatusesRequest() {
    try {
        if (bStopListJobStatusesResponseProcessing)
            return;
        const oJobStatuses = (await AsyncSendRecivePostApi("ListJobStatuses", {})).response.result;
        if (bStopListJobStatusesResponseProcessing)
            return;
        await 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 glob.GetJobArr()) {
                    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";
                        }
                        await ShowTextIfNoTree(item);
                    }
                }
                if (err.code < 0 && nServerDisconnectCycle > 2) {
                    if (SetDomDisplayAndInnerHtml(domHtmlErr, "flex", { text: "<div>" + err.message + "</div>" })) {
                        if (domModal.style.zIndex != "12345678") {
                            oOldMyModalPar.zIndex = domModal.style.zIndex;
                            oOldMyModalPar.display = domModal.style.display;
                            domModal.style.zIndex = "12345678";
                            domModal.style.display = "";
                        }
                    }
                }
            }
        }
    }
}
let bGlobalWaitingBoxFlag = false;
async function ListJobStatusesResponseProcessing(jsJobinfo) {
    if (!jsJobinfo.job_statuses || !jsJobinfo.job_statuses.length)
        return;
    if (!bExtraJobsDetected && jsJobinfo.job_statuses.length < glob.GetJobArr().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 = glob.GetJobInList(sJobName);
        let bNewMode = false;
        if (!oJobInList) {
            try {
                oJobInList = await glob.PutJobToList(sJobName, i);
                bIsNewJob = true;
                bNewRunState = true;
            }
            catch {
                continue;
            }
        }
        else {
            if (oJobInList.oJobStatus) {
                bNewRunState = oJobInList.oJobStatus.job_run_state !== iJS.job_run_state;
                if (oJobInList.oJobStatus.view_mode === undefined) {
                    oJobInList.oJobStatus.view_mode = iJS.view_mode;
                }
                else if (oJobInList.oJobStatus.view_mode != iJS.view_mode && sJobName == sCurrJob) {
                    bNewMode = true;
                }
                if (oJobInList.oJobStatus.last_mod_time != iJS.last_mod_time) {
                    const aJobStructs = await JobListWithSmallDataRequest(aJobFieldsForTable, [sJobName]);
                    if (aJobStructs && aJobStructs.length === 1 && aJobStructs[0].opt) {
                        SettingJobShortFields(aJobStructs[0].opt, oJobInList);
                        if (jsJobsTables[sJobName]) {
                            jsJobsTables[sJobName].fClear();
                            if (jsJobsTables[sJobName].domLimWindow) {
                                jsJobsTables[sJobName].domLimWindow.innerHTML = "";
                            }
                            delete jsJobsTables[sJobName];
                        }
                        if (sJobName == sCurrJob) {
                            FillRightWindow(true);
                        }
                        bIsDiffers = true;
                    }
                }
            }
        }
        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) {
            glob.ChangeIconOfGroupJobs(sJobName, oJobInList.job_icon);
            bIsDiffers = true;
            if (IsJobStateWoTree(oState)) {
                delete jsJobsTables[sJobName];
                delete oJobInList.aTotals;
            }
        }
        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) {
                            await 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");
                        await ShowTextIfNoTree(oJobInList);
                    }
                    break;
                case "analyze_running":
                    {
                        DeactivateClassEl("btn_sync_and_analize");
                        EnableClassEl("btn_stop_job");
                        if (bNewRunState) {
                            await 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;
                        }
                        if (oJobInList.bBlockTree) {
                            delete oJobInList.bBlockTree;
                        }
                    }
                    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)
                            && oJobInList.oJobStatus.nItemsChanged !== 0) {
                            ActivateClassEl("btn_sync");
                        }
                        else {
                            DeactivateClassEl("btn_sync");
                        }
                        if (bLastRunTimeIsChanged || bNewMode) {
                            if (jsJobsTables[sJobName] && jsJobsTables[sJobName].fIsNotEmpty()) {
                                RefreshJobTreeRequest(sJobName);
                            }
                            else {
                                if (jsJobsTables[sJobName]) {
                                    if (jsJobsTables[sJobName].domLimWindow) {
                                        jsJobsTables[sJobName].domLimWindow.innerHTML = "";
                                    }
                                    delete jsJobsTables[sJobName];
                                }
                                JobTreeRequest();
                                await ShowTextIfNoTree(oJobInList);
                            }
                        }
                        else if (bNewRunState) {
                            if (!jsJobsTables[sJobName] || !jsJobsTables[sJobName].fIsNotEmpty()) {
                                JobTreeRequest(sJobName);
                                await ShowTextIfNoTree(oJobInList);
                            }
                            else {
                                await ShowTreeIfThisNeeds(sJobName, jsJobsTables[sJobName]);
                            }
                        }
                        if (oJobInList.bBlockTree) {
                            delete oJobInList.bBlockTree;
                        }
                        const domBlockTree = document.getElementById("tree_block");
                        if (domBlockTree) {
                            domBlockTree.style.display = "none";
                        }
                    }
                    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 || bNewMode) {
                            if (!jsJobsTables[sJobName]) {
                                JobTreeRequest(sJobName);
                                await ShowTextIfNoTree(oJobInList);
                            }
                            else {
                                await ShowTreeIfThisNeeds(sJobName, jsJobsTables[sJobName], oJobInList);
                            }
                        }
                        else if (!mapNextTreeChangeIds.has(sJobName)
                            || iJS.next_tree_change_id > mapNextTreeChangeIds.get(sJobName)
                            || (oState == "sync_running") && (GetCurrTime() - dtLastTreeChangeRecuest) > 1000) {
                            await JobTreeChangesRequest(sJobName);
                        }
                        if (oJobInList.bBlockTree) {
                            delete oJobInList.bBlockTree;
                        }
                        const domBlockTree = document.getElementById("tree_block");
                        if (domBlockTree) {
                            domBlockTree.style.display = "none";
                        }
                    }
                    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)) {
                            await 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)
                            && oJobInList.oJobStatus.nItemsChanged !== 0) {
                            ActivateClassEl("btn_sync");
                        }
                        else {
                            DeactivateClassEl("btn_sync");
                        }
                        if (oJobInList.bNeedRefreshAfterSpOp || bNewMode) {
                            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)) {
                            await JobTreeChangesRequest(sJobName);
                        }
                        const domBlockTree = document.getElementById("tree_block");
                        if (domBlockTree) {
                            domBlockTree.style.display = "none";
                        }
                        if (oJobInList.bBlockTree) {
                            delete oJobInList.bBlockTree;
                        }
                    }
                    break;
                case "not_connected":
                    {
                        EnableClassEl("btn_sync_and_analize");
                        ActivateClassEl("btn_analize");
                        DeactivateClassEl("btn_sync");
                        DisableClassEl("btn_stop_job");
                        if (bNewRunState) {
                            await 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;
        }
    }
    if (bIsNewJob) {
        localStorage.setItem("oSavedData", JSON.stringify(oSavedData));
    }
    glob.JustRefreshAllJobTables(bIsDiffers || bIsNewJob);
    if (!bLastPrevSessionJobWasOpend) {
        if (!bIsNewJob) {
            glob.MarkJobInJobList();
        }
    }
}
async function OneTreeLineRequest(arr) {
    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": glob.GetTreeMode(sCurrJob), "start_from": sFName, "max_items": 1 };
        const jsJobTree = await SendRecivePostApiWithRetry("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) {
    }
}
async function SetJobOptions(jsOpt, oFCO) {
    let bWasSideChange = false;
    if (oFCO) {
        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;
            if (jsOpt.eJobDirection === JS_TWO_WAY) {
                jsOpt.bFastNoState1way = false;
                jsOpt.bIgnoreChangesOnDestSide = false;
                jsOpt.bMoveMode_DeleteSourceAfterCopy = false;
            }
        }
    }
    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;
            }
        }
    }
    if (jsOpt.iEveryHour === 0 && jsOpt.iEveryMinute === 0) {
        jsOpt.atOnTimer = 0;
    }
    try {
        await SetJobOptionsRequest(jsOpt);
        if (sCurrJob === jsOpt.sName) {
            FillRightWindow(bWasSideChange);
        }
    }
    catch (oErr) {
        if (sCurrJob === jsOpt.sName) {
            FillRightWindow(bWasSideChange);
        }
        throw oErr;
    }
}
async function SetJobOptionsRequest(jsOpt) {
    const oJobInList = glob.GetJobInList(jsOpt.sName);
    let bAutoRunSuspend = true;
    try {
        if (IsJobActive(jsOpt.sName)) {
            await AsyncHtmlConfirm("Qsn_DoYouWantStopJob", "Cnfrm_SetJobOptions", eMyConfDefBtn.ok);
            if (oJobInList && oJobInList.bHaveAutoOpt) {
                bAutoRunSuspend = await GetCommonAutoRun();
                if (!bAutoRunSuspend) {
                    await SetCommonAutoRun(true);
                }
            }
            await StopRequest(jsOpt.sName, true, true);
        }
        const jsJobinfo = await SendRecivePostApiWithRetry("SetJobOptions", { "job_name": jsOpt.sName, "options": jsOpt });
        if (!bAutoRunSuspend) {
            await 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";
        }
        glob.SettingJobInListFields(jsJobinfo.new_options, jsOpt.sName);
        localStorage.setItem("oSavedData", JSON.stringify(oSavedData));
        FillCurrJobDetalesWindow(true);
    }
    catch (oErr) {
        throw oErr;
    }
}
function SetSwitchJobModePanel(oJobInList) {
    if (oJobInList) {
        CreatePanelOfJobModeView(oJobInList.aTotals, glob.GetTreeMode(oJobInList.name));
    }
}
async function JobTreeReqAndProc(oParams, oTableRow) {
    try {
        let oJobTree = await SendRecivePostApiWithRetry("ReadJobTree", oParams, { oMultiPageArrs: { tree: [], totals: [], next_name: "" }, nMaxArrLen: 1000 });
        if ("server_view_mode" in oJobTree) {
            oParams.view_mode = oJobTree.server_view_mode;
            glob.SetTreeMode(oParams.job_name, oJobTree.server_view_mode);
            oJobTree = await SendRecivePostApiWithRetry("ReadJobTree", oParams, { oMultiPageArrs: { tree: [], totals: [], next_name: "" }, nMaxArrLen: 1000 });
        }
        const jsTmpJobTree = oJobTree.tree;
        const oJobInList = glob.GetJobInList(oParams.job_name);
        if (oJobTree.totals.length > 1 && oJobInList) {
            oJobInList.aTotals = oJobTree.totals;
        }
        let oDTP = jsJobsTables[oParams.job_name];
        if (jsTmpJobTree.length > 0) {
            if (oDTP) {
                if (oTableRow) {
                    oTableRow.fAddDataArr(jsTmpJobTree, { oDTP, bClean: !oParams.start_from });
                }
                else {
                    oDTP.root.cont[0].fAddDataArr(jsTmpJobTree, { oDTP, bClean: !oParams.start_from });
                }
            }
            else {
                oDTP = new CDynTabProp();
                oDTP.aHead = jsJobTreeTableHead;
                oDTP.bStriped = true;
                oDTP.bIsTree = true;
                oDTP.bNoneScrollX = true;
                oDTP.fOpenFolder = (oBr) => {
                    JobTreeRequest("", oBr);
                };
                oDTP.fRightBtn = JobTreeRightButtonFunc;
                oDTP.sPathFieldName = "name";
                oDTP.sSortCol = "name";
                oDTP.fDataProcessor = SetFoldAndClass;
                oDTP.fAutoDeploy = async (oBr) => {
                    await JobTreeReqAndProc({ "job_name": oParams.job_name, "path": oBr.fGetPathStr("/"), "view_mode": glob.GetTreeMode(oParams.job_name), "max_items": READ_JOB_TREE_MAX_ITEM }, oBr);
                };
                oDTP.sAutoDeploy = "JobTreeAutoDeploy";
                oDTP.nMinRowHeight = 1.25 + (2 - oSavedData.oOpts.eTreeDisplayDensity) * 0.25;
                oDTP.root.fAddDataArr([{
                        name: oJobInList.name, job_node: true, changes: !(!oJobInList.aTotals || !oJobInList.aTotals[1]),
                        data: { lcur: { "filled": true, "is_folder": true, }, rcur: { "filled": true, "is_folder": true, }, lold: {}, rold: {} }
                    }], { oDTP });
                oDTP.root.cont[0].bNoSelectWithShiftOrCtrl = true;
                oDTP.root.cont[0].fCloseFolder = () => {
                    oDTP.root.cont[0].fCloseAllFoldersDown();
                };
                oDTP.root.cont[0].fGetPathStr = () => { return ""; };
                oDTP.root.cont[0].fGetPathArr = () => { return []; };
                oDTP.root.cont[0].folder = FOLDER_OPEN;
                oDTP.root.cont[0].fAddDataArr(jsTmpJobTree, { oDTP, bClean: !oParams.start_from });
                oDTP.root.cont[0].fRightBtn = (e, oBranch, oDTP) => {
                    DeleteAllDropMenu();
                    CreateDropMenuItems(jsUserActsMenu.job, e.clientX, e.clientY, e.clientX, e.target, false, oJobInList);
                };
                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, oSavedData.aJobTreeNarrowTableColsSize);
                    }
                    else {
                        CopyEqSizeArray(oDTP.aTableColsWidth, oSavedData.aJobTreeWideTableColsSize);
                    }
                    localStorage.setItem("oSavedData", JSON.stringify(oSavedData));
                };
                oDTP.fGetColsSizeFromLocStor = () => {
                    if (bJobTreeNarrowMode) {
                        if (oSavedData.aJobTreeNarrowTableColsSize && oSavedData.aJobTreeNarrowTableColsSize.length) {
                            CopyEqSizeArray(oSavedData.aJobTreeNarrowTableColsSize, oDTP.aTableColsWidth);
                            return true;
                        }
                    }
                    else {
                        if (oSavedData.aJobTreeWideTableColsSize && oSavedData.aJobTreeWideTableColsSize.length) {
                            CopyEqSizeArray(oSavedData.aJobTreeWideTableColsSize, oDTP.aTableColsWidth);
                            return true;
                        }
                    }
                    return false;
                };
                jsJobsTables[oParams.job_name] = oDTP;
            }
        }
        else if (oTableRow) {
            oTableRow.folder = FOLDER_EMPTY;
        }
        else if (oDTP) {
            oDTP.fClear();
            delete jsJobsTables[oParams.job_name];
        }
        if (oJobTree.next_name) {
            const oParams2 = {
                "job_name": oParams.job_name,
                "path": oParams.path,
                "view_mode": glob.GetTreeMode(oParams.job_name),
                "start_from": oJobTree.next_name,
                "max_items": READ_JOB_TREE_MAX_ITEM
            };
            const aFunc = { fDblclick: async () => {
                    await JobTreeReqAndProc(oParams2, oTableRow);
                    await DisplayJobTree(oParams.job_name, oParams.path, oDTP);
                } };
            if (oTableRow) {
                oTableRow.fAddDataArr([{ "name": "@" }], { oFunc: aFunc, fDataProcessor: SetNextDataButton, oDTP });
            }
            else {
                oDTP.root.cont[0].fAddDataArr([{ "name": "@" }], { oFunc: aFunc, fDataProcessor: SetNextDataButton, oDTP });
            }
        }
        if (oTableRow) {
            delete oTableRow.oIsWaiting;
        }
        return oDTP;
    }
    catch (oErr) {
        if (oErr && 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;
            }
        }
    }
}
async function SpOpRequestFromJobsList(text, xJobName) {
    const oSpOpCod = GetSpOp(text);
    if (!oSpOpCod || !oSpOpCod.sp_op) {
        HtmlMsgbox("Command \"" + GetLocaleText(text) + "\" not implemented ");
        return;
    }
    let aJobNames = [];
    if (!xJobName) {
        xJobName = { DTP: glob.GetActiveJobTable() };
    }
    if (typeof xJobName === 'string') {
        aJobNames[0] = xJobName;
    }
    else if (xJobName.DTP) {
        const nSelTabLen = xJobName.DTP.fGetSelTabLen();
        if (nSelTabLen > 0) {
            for (let i = 0; i < nSelTabLen; i++) {
                aJobNames.push(xJobName.DTP.fGetSelBranch(i).fGetData().name);
            }
        }
        else {
            aJobNames[0] = xJobName.Branch.fGetData().name;
        }
    }
    let sQuestion = "";
    let sTitle = "";
    switch (oSpOpCod.sp_op) {
        case SpOp_DeleteStateFiles:
            {
                sQuestion = "Str_AskDeleteStates1";
                sTitle = "Str_TitleResetState";
            }
            break;
        case SpOp_DeleteRecycledAndHistory:
            {
                sQuestion = "Str_AskDeleteBackup1";
                sTitle = "Str_TitleDeleteBackup";
            }
            break;
        case SpOp_DeleteGsData_Both:
            {
                sQuestion = "Str_AskDeleteGsData1";
                sTitle = "Str_TitleDeleteGsData";
            }
            break;
    }
    const aErrs = [];
    try {
        if (sQuestion) {
            await AsyncHtmlConfirm(GetLocaleText(sQuestion, [aJobNames.join("<br>")]), sTitle, eMyConfDefBtn.none);
        }
        for (const sJobName of aJobNames) {
            try {
                await SendRecivePostApiWithRetry("StartSpecOp", { "job_name": sJobName, "spop_type": oSpOpCod.sp_op });
            }
            catch (oErr) {
                if (oErr && oErr.error) {
                    aErrs.push(sJobName + ": " + oErr.error.message);
                }
                continue;
            }
            if (oSpOpCod.sp_op == SpOp_DeleteGsData_Left || oSpOpCod.sp_op == SpOp_DeleteGsData_Right || oSpOpCod.sp_op == SpOp_DeleteGsData_Both) {
                delete jsJobsTables[sJobName];
                if (sJobName == sCurrJob) {
                    ShowTextIfNoTree(glob.GetJobInList(sJobName), false, true);
                }
                setNeedResetJob.add(sJobName);
            }
        }
    }
    catch (oErr) {
        if (aErrs.length > 0) {
            ErrorMsgShow(aErrs.join("<br>"));
        }
        else if (oErr && oErr.error) {
            ErrorMsgShow(oErr.error.message);
        }
    }
}
async function ResetJob(sJobName) {
    await SendRecivePostApiWithRetry("ResetJob", { "job_name": sJobName });
    setNeedResetJob.delete(sJobName);
    delete jsJobsTables[sJobName];
}
async function DeleteGsDataFolderRequest(sJobName, bLeftSide) {
    let text = "Title_JobRightSide";
    let nSpOp = SpOp_DeleteGsData_Right;
    if (bLeftSide) {
        text = "Title_JobLeftSide";
        nSpOp = SpOp_DeleteGsData_Left;
    }
    try {
        await SendRecivePostApiWithRetry("StartSpecOp", { "job_name": sJobName, "spop_type": nSpOp });
    }
    catch (oErr) {
        CatchErrProcess(oErr);
    }
}
function RefreshJobTreeBranch(oBranchProp) {
    RefreshJobTreeRequest(sCurrJob, oBranchProp.path_arr[0]);
}
function SpOpRequest(text, oBranchProp) {
    SpOpRequest2(text, oBranchProp.path_arr);
}
async function SpOpRequest2(text, aItemPaths = [""]) {
    const oSpOpCod = GetSpOp(text);
    if (!oSpOpCod) {
        HtmlMsgbox("There is not user act \"" + text + "\" for " + aItemPaths[0]);
        return;
    }
    const sJobName = sCurrJob;
    if (oSpOpCod.sp_op) {
        let aPath = [];
        for (const item of aItemPaths) {
            aPath.push({ "path": (item ? "\/" + item : ""), "action": oSpOpCod.user_act });
        }
        const oJobInList = glob.GetJobInList(sJobName);
        const domBlockTree = document.getElementById("tree_block");
        if (oJobInList && domBlockTree) {
            oJobInList.bBlockTree = true;
            domBlockTree.style.display = "";
        }
        try {
            await SendRecivePostApiWithRetry("StartSpecOp", { "job_name": sJobName, "spop_type": oSpOpCod.sp_op, "paths_actions": aPath, "req_view_mode": glob.GetTreeMode(sJobName) });
        }
        catch {
            if (oJobInList) {
                delete oJobInList.bBlockTree;
            }
            if (domBlockTree) {
                domBlockTree.style.display = "none";
            }
        }
    }
    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);
            }
        }
        const oFCO = new CForChangeOptions;
        JobOptionsForChangeRequest(oFCO, false, oFilters);
    }
}
async function FileSysWindSettingRequest(domWindow, sUrl, oJobInList, bLeft) {
    if (!domWindow || !sUrl)
        return;
    try {
        const ans = await SendRecivePostApiWithRetry("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";
        }
        const img = SetImg(sIcon, "var(--job-detale-img-size)", "abs_pos_img");
        domWindow.innerHTML = "";
        if (img) {
            domWindow.append(img);
        }
        if (oJobInList) {
            if (bLeft) {
                oJobInList.iconFsL = sIcon;
            }
            else {
                oJobInList.iconFsR = sIcon;
            }
        }
    }
    catch { }
}
async function ListAccForExplorerRequest(oIFDD, oBDE, bDontOpen) {
    if (!oBDE.DTP || !oBDE.Branch || oBDE.Branch.oIsWaiting) {
        return;
    }
    if (oBDE.Branch.bError) {
        oBDE.Branch.fClear();
    }
    else if (oBDE.Branch.cont && oBDE.Branch.cont.length > 0) {
        if (bDontOpen)
            return;
        if (!oIFDD) {
            oBDE.Branch.folder = FOLDER_OPEN;
            oBDE.DTP.ShowTable();
            return;
        }
        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 = FOLDER_OPEN;
            oTargetBranch.folder = FOLDER_OPEN;
            oBDE.DTP.ShowTable();
            await 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, { bDontOpen });
    const sFsUrl = GetFieldValWithDrillUp(oBDE.Branch, "sFs");
    const oParams = { "fs_url": sFsUrl };
    try {
        const oAccList = await SendRecivePostApiWithRetry("ListAccounts", oParams, { oMultiPageArrs: { accounts: [], hints: [] }, abort: oData.__oAbort__ });
        if (!oAccList) {
            return;
        }
        const aAccounts = SetBrowsTreeAccounts(oAccList.accounts, oAccList.hints);
        await ListAccountsForExplorerResponseProcessing(aAccounts, oIFDD, oBDE, bDontOpen);
    }
    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);
        }
    }
}
async function FindServerAndFolder(oTargetBranch, oIFDD, oBDE, bDontOpen) {
    if (!oBDE.DTP)
        return;
    oBDE.Branch = oTargetBranch;
    oTargetBranch.fMarkAndShow(oBDE.DTP);
    await TableRowClick(oBDE.DTP, oTargetBranch, bDontOpen);
    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("Home Path of account (" + sHomePath + ") not in path " + oIFDD.conn.sUrlA);
            return;
        }
    }
    const aJobPath = (url.hostname + "/" + url.pathname).split('/');
    if (aJobPath.length > 1 && aJobPath[aJobPath.length - 1] === "") {
        aJobPath.splice(aJobPath.length - 1);
    }
    const sFsName = GetFieldValWithDrillUp(oTargetBranch, "sFs");
    if (IsFsGST(sFsName) || oData.bContServList) {
        aJobPath[0] = sFsName + aJobPath[0];
    }
    if (oData.bContServList) {
        await ListServersRequest(oIFDD.conn, aJobPath, oBDE, bDontOpen);
    }
    else {
        aJobPath.splice(0, 1);
        await ConnectFsRequest(oData.oConn, aJobPath, oBDE, {}, bDontOpen);
    }
}
async function ListAccountsForExplorerResponseProcessing(aAcc, oIFDD, oBDE, bDontOpen) {
    if (!oBDE.DTP || !oBDE.Branch) {
        return;
    }
    oBDE.Branch.fClear();
    if (!oIFDD) {
        oBDE.Branch.fAddDataArr(aAcc, { fDataProcessor: ProcessAccBranchForTable, sPathFieldName: "sAccKey" });
        if (!bDontOpen) {
            oBDE.Branch.folder = FOLDER_OPEN;
            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);
    }
    if (bDontOpen)
        return;
    if (oIFDD.conn.sUrlA.endsWith("://")) {
        if (oTargetBranch && oTargetBranch.pathEl == oIFDD.conn.sUrlA) {
            oTargetBranch.fMarkAndShow(oBDE.DTP);
            if (oSavedData.IsWinMode()) {
                TableRowClick(oBDE.DTP, oTargetBranch, true);
            }
            else {
                TableOpenFolder(oBDE.DTP, oTargetBranch, true);
            }
        }
        else {
            if (oSavedData.IsWinMode()) {
                oBDE.Branch.folder = FOLDER_CLOSE;
                oBDE.Branch.fMarkAndShow(oBDE.DTP);
                TableRowClick(oBDE.DTP, oBDE.Branch, true);
            }
            else {
                oBDE.Branch.fMarkAndShow(oBDE.DTP);
                TableOpenFolder(oBDE.DTP, oBDE.Branch, true);
            }
        }
        return;
    }
    oBDE.Branch.folder = FOLDER_OPEN;
    oBDE.DTP.ShowTable();
    if (oTargetBranch) {
        await FindServerAndFolder(oTargetBranch, oIFDD, oBDE, bDontOpen);
    }
    else if (oBDE.Branch.cont && oBDE.Branch.cont.length === 1) {
        await FindServerAndFolder(oBDE.Branch.cont[0], oIFDD, oBDE, bDontOpen);
    }
    else {
        AddErrorToTree({ message: "Incorrect or missing account " + oIFDD.key, data: { error_num: -1, error_str: "" } }, oBDE);
    }
}
async function ListServersRequest(oConn, aJobPath, oBDE, bDontOpen) {
    if (!oBDE.Branch || !oBDE.DTP) {
        return;
    }
    if (oBDE.Branch && oBDE.Branch.cont && oBDE.Branch.cont.length > 0) {
        if (bDontOpen)
            return;
        oBDE.Branch.folder = FOLDER_OPEN;
        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;
            await 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, { bDontOpen });
    try {
        const oServList = await SendRecivePostApiWithRetry("ListServers", { "conn": oConn }, { abort: oData.__oAbort__ });
        await ListServersResponseProcessing(oServList, aJobPath, oConn, oBDE, bDontOpen);
    }
    catch (oErr) {
        if (oErr && oErr.error && oErr.error.data && !bDontOpen) {
            if (oErr.error.data.error_str == "needs_custom_gui_auth") {
                if (!GetFieldValWithDrillUp(oBDE.Branch, "bAuthOauth2")) {
                    try {
                        await StartTwoFactorAuth(oConn);
                        await ListServersRequest(oConn, aJobPath, oBDE);
                    }
                    catch {
                        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);
            }
        }
        else {
            SendRecivePostApiCatch(oErr, "ListServerss err: ", oBDE);
        }
    }
}
async function ListServersResponseProcessing(jsData, aJobPath, oConn, oBDE, bDontOpen) {
    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);
    if (aJobPath && aJobPath.length === 1) {
        const oData = oBDE.Branch.fGetData();
        if (aJobPath[0] === oData.oConn.sUrlA) {
            if (oSavedData.IsWinMode()) {
                oBDE.Branch.folder = FOLDER_CLOSE;
                oBDE.DTP.ShowTable();
                await TableRowClick(oBDE.DTP, oBDE.Branch, true);
            }
            else {
                oBDE.DTP.ShowTable();
                await TableOpenFolder(oBDE.DTP, oBDE.Branch, true);
            }
            return;
        }
    }
    if (bDontOpen)
        return;
    if (oConn && aJobPath && aJobPath.length > 0) {
        oBDE.Branch.folder = FOLDER_OPEN;
        oBDE.DTP.ShowTable();
        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;
            await ConnectFsRequest(oConn, aJobPath, oBDE, {});
        }
        else {
            HtmlErrBox("Incorrect server name " + aJobPath[0], "Err_BrowseDialog");
        }
    }
    else if (aJobPath) {
        if (oSavedData.IsWinMode()) {
            oBDE.Branch.folder = FOLDER_CLOSE;
            oBDE.DTP.ShowTable();
            await TableRowClick(oBDE.DTP, oBDE.Branch, true);
        }
        else {
            oBDE.DTP.ShowTable();
            await TableOpenFolder(oBDE.DTP, oBDE.Branch, true);
        }
    }
    else {
        oBDE.DTP.ShowTable();
    }
}
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);
    }
}
async function DisconnectFsRequest(filesys_handle) {
    try {
        await SendRecivePostApiWithRetry("DisconnectFS", { "filesys_handle": filesys_handle });
    }
    catch { }
    mapFsReestr.delete(filesys_handle);
}
async function ConnectFsRequestPromise(oFC) {
    try {
        return await SendRecivePostApiWithRetry("ConnectFS", { "folder_coords": oFC });
    }
    catch (err) {
        throw err;
    }
}
async function FsDataRequest(folder_coords, request_free_space, abort) {
    return await SendRecivePostApiWithRetry("ConnectFS", { folder_coords, request_free_space }, { abort });
}
async function ConnectFsRequest(oConn, aJobPath, oBDE, oPar, bDontOpen) {
    if (!oBDE.DTP || !oBDE.Branch)
        return;
    const oData = oBDE.Branch.fGetData();
    if (oBDE.Branch && oBDE.Branch.cont && oBDE.Branch.cont.length > 0) {
        if (bDontOpen) {
            return;
        }
        if (oPar.dNeedBranchInfo) {
            await SetBeJobSideAbility(oData, oBDE);
            return;
        }
        oBDE.Branch.folder = FOLDER_OPEN;
        oBDE.DTP.ShowTable();
        if (aJobPath && aJobPath.length > 0) {
            await ListDirForExplorerRequest(oData.sHomePath ? oData.sHomePath : "", aJobPath, oBDE, { bDontOpen, dNeedBranchInfo: oPar.dNeedBranchInfo });
        }
        return;
    }
    if (!oData.__oAbort__) {
        oData.__oAbort__ = new AbortController();
    }
    ShowWaitingTimer("Connecting", oBDE, { bDontOpen });
    const oFolderCoords = { "conn": oConn, "sAcctKeyA": oData.fGetAccKey(), };
    if (oPar.oBM) {
        oFolderCoords.opts = oPar.oBM.Opts;
        oFolderCoords.sServerDirA = oPar.oBM.sServerDirA || oPar.oBM.BmkKey || "";
        oFolderCoords.sBmkNameA = oFolderCoords.sServerDirA;
        oFolderCoords.conn = CopyObject(oConn);
        if (IsFsGST(oFolderCoords.conn.sUrlA)) {
            const sServerName = GetGstServerName(oFolderCoords.conn.sUrlA, oFolderCoords.conn.sUserIdA);
            if (sServerName && oFolderCoords.sServerDirA.startsWith(sServerName)) {
                oFolderCoords.conn.sUrlA += oFolderCoords.sServerDirA.slice(sServerName.length);
            }
            else {
                oFolderCoords.conn.sUrlA += oFolderCoords.sServerDirA;
            }
        }
        else {
            oFolderCoords.conn.sUrlA += oFolderCoords.sServerDirA;
        }
    }
    else if (oData.bIgnoreBookmark) {
        oFolderCoords.conn = CopyObject(oConn);
        oFolderCoords.conn.sUrlA += oData.sHomePath;
    }
    try {
        const jsData = await SendRecivePostApiWithRetry("ConnectFS", { "folder_coords": oFolderCoords, "request_free_space": !oPar.oBM, }, { "abort": oData.__oAbort__ });
        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 (oPar.bOnlyEncFsHandle)
            return;
        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 && IsBmEncOrZip(oData.oBookmarkAcc.Opts) && !oData.bIgnoreBookmark && !oData.sFsHandleEnc) {
            await ConnectFsRequest(oData.oConn, aJobPath, oBDE, { oBM: oData.oBookmarkAcc }, bDontOpen);
        }
        else {
            await ListDirForExplorerRequest(oData.oBookmarkAcc ? "" : oData.sHomePath ? oData.sHomePath : "", aJobPath, oBDE, { bDontOpen, sNameForMark: oPar.sFolderName, dNeedBranchInfo: oPar.dNeedBranchInfo });
        }
    }
    catch (oErr) {
        if (oErr) {
            if (oErr.error && 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 = await CredentialsRequest("Authentication", "Authentication of " + oConn.sUrlA, oTmp);
                                    oConn.sUserIdA = data.arr[0].value;
                                    try {
                                        oConn.sPasswordEncMasterA = await EncryptStringWithKey(data.arr[1].value, oSavedData.key, oSavedData.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, { jsAccData: oAccPar });
                                    }
                                    catch {
                                        AddErrorToTree({ message: "Authentication failed", data: { error_num: -1, error_str: "Authentication_failed" } }, oBDE);
                                    }
                                }
                                else {
                                    const pAcc = GetAccWithCreds(oConn, oBDE.DTP);
                                    if (pAcc && pAcc != oBDE.Branch.pParent) {
                                        CleanAndCloseBranch(oBDE);
                                        if (pAcc.fOpenFolder) {
                                            pAcc.fMarkSelf(oBDE.DTP);
                                            oBDE.DTP.ShowFirstSelectRow();
                                            await pAcc.fOpenFolder(pAcc, oBDE.DTP);
                                        }
                                    }
                                    else {
                                        const oTmp = { arr: [{ title: "Login: ", value: "" }, { title: "Password: ", value: "", password: true }] };
                                        const data = await CredentialsRequest("Authentication", "Authentication of " + oConn.sUrlA, oTmp);
                                        const oTmpConn = CopyObject(oConn);
                                        ;
                                        oTmpConn.sUserIdA = data.arr[0].value;
                                        try {
                                            oTmpConn.sPasswordEncMasterA = await EncryptStringWithKey(data.arr[1].value, oSavedData.key, oSavedData.iv);
                                            oBDE.Branch.fClear();
                                            oBDE.Branch.folder = FOLDER_CLOSE;
                                            if (oBDE.Branch && oBDE.Branch.pParent && oBDE.Branch.pParent.pParent) {
                                                oBDE.Branch = oBDE.Branch.pParent.pParent;
                                                CreateAccountRequest(oTmpConn, "", oBDE);
                                            }
                                        }
                                        catch {
                                            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;
                                    }
                                    await 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.OAuth2ConnectRequest(oConn, menuWait.oMenu.id);
                                }
                                else {
                                    await 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 {
                    CleanAndCloseBranch(oBDE);
                }
            }
            else if (oErr.message) {
                ErrorMsgShow(oErr.message, { eGoal: "console", sErrType: "ConnectFsResponseProcessing" });
            }
            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" });
            }
        }
    }
}
const LIST_DIR_MAX_ITEM = 1000;
async function ListDirRequestPromise(sFsHandle, sPath, sNextPage, nMaxItems) {
    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 await SendRecivePostApiWithRetry("ListDir", oParams);
    }
    catch (err) {
        throw err;
    }
}
async function ListDirRequestWithReconnect(oParams, oSRP, oBDE, nMaxItems) {
    if (!nMaxItems) {
        nMaxItems = LIST_DIR_MAX_ITEM;
    }
    try {
        oParams.filesys_handle = await oFsHandle.get(oBDE.Branch);
        const ans = await SendRecivePostApiWithRetry("ListDir", oParams, oSRP);
        oFsHandle.del(oParams.filesys_handle);
        return ans;
    }
    catch (oErr) {
        oFsHandle.del(oParams.filesys_handle);
        if (oErr && oErr.error && oErr.error.data && oErr.error.data.error_str == "disconnected" && oBDE.Branch) {
            try {
                const oData = oBDE.Branch.fGetData();
                const { fs_handle, fs_data } = await oFsHandle.getNew(oBDE.Branch, true);
                if (oData.fSetFsHandle) {
                    oData.fSetFsHandle(fs_handle);
                }
                if (fs_data && oParams.request_free_space && fs_data.root_free_space_info) {
                    const oDiscTotal = ConvertBytes(fs_data.root_free_space_info.total);
                    const oDiscFree = ConvertBytes(fs_data.root_free_space_info.available);
                    const pos = oData.comment.indexOf("Total: ");
                    if (pos >= 0) {
                        oData.comment.slice(pos);
                    }
                    oData.comment += "Total: " + oDiscTotal.nSpace1 + " " + oDiscTotal.unit + ", Free Space: " + oDiscFree.nSpace1 + " " + oDiscFree.unit;
                }
                oParams.filesys_handle = fs_handle;
                return await SendRecivePostApiWithRetry("ListDir", oParams, oSRP);
            }
            catch (oErr2) {
                throw oErr2;
            }
        }
        else if (oErr && oErr.error && oErr.error.data && oErr.error.data.error_str == "bad_page_token" && oBDE.Branch) {
            oBDE.Branch.fClear();
            const ans = await SendRecivePostApiWithRetry("ListDir", oParams, oSRP);
            return ans;
        }
        else {
            throw oErr;
        }
    }
}
async function RequestWithReconnect(command, oParams, oBDE) {
    try {
        oParams.filesys_handle = await oFsHandle.get(oBDE.Branch);
        const ans = await SendRecivePostApiWithRetry(command, oParams);
        oFsHandle.del(oParams.filesys_handle);
        return ans;
    }
    catch (oErr) {
        oFsHandle.del(oParams.filesys_handle);
        if (oErr && oErr.error && oErr.error.data && oErr.error.data.error_str == "disconnected" && oBDE.Branch) {
            try {
                let oData = oBDE.Branch.fGetData();
                while (!oData.oConn && oBDE.Branch.pParent) {
                    oData = oBDE.Branch.pParent.fGetData();
                }
                const sAcctKeyA = oData.fGetAccKey ? oData.fGetAccKey() : "";
                const oFsData = await SendRecivePostApiWithRetry("ConnectFS", { folder_coords: { conn: oData.oConn, sAcctKeyA }, request_free_space: oParams.request_free_space });
                oParams.filesys_handle = oFsData.filesys_handle;
                if (oData.fSetFsHandle) {
                    oData.fSetFsHandle(oFsData.filesys_handle);
                }
                return await SendRecivePostApiWithRetry(command, oParams);
            }
            catch (oErr2) {
                throw oErr2;
            }
        }
        else {
            throw oErr;
        }
    }
}
async function ListDirForExplorerRequest(sPath, aJobPath, oBDE, oLDP) {
    if (!oBDE.DTP || !oBDE.Branch || oBDE.Branch.folder === FOLDER_EMPTY || oBDE.Branch.folder === FOLDER_IS_HIDE_IN)
        return;
    if (oLDP.dNeedBranchInfo && !aJobPath) {
        const nOldFolder = oBDE.Branch.folder;
        oBDE.Branch.fClear();
        oBDE.DTP.ShowTable();
        await TableRowClick(oBDE.DTP, oBDE.Branch, true);
        if (nOldFolder == FOLDER_OPEN) {
            await TableOpenFolder(oBDE.DTP, oBDE.Branch, true);
            oBDE.Branch.folder = FOLDER_OPEN;
            oBDE.DTP.ShowTable();
        }
        return;
    }
    if (oBDE.Branch && oBDE.Branch.cont && oBDE.Branch.cont.length > 0 && !oBDE.Branch.oIsWaiting && !oBDE.Branch.bError) {
        if (oLDP.bDontOpen)
            return;
        oBDE.Branch.folder = FOLDER_OPEN;
        oBDE.DTP.ShowTable();
        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.fMarkSelf(oBDE.DTP);
                const oNextData = oNextBranch.fGetData();
                if (oNextData.oBookmark && oNextData.sFsHandle && !oNextData.bIgnoreBookmark) {
                    sPath = "";
                }
                else {
                    sPath += "/" + aJobPath[0];
                }
                aJobPath.splice(0, 1);
                oBDE.Branch = oNextBranch;
                TableRowClick(oBDE.DTP, oNextBranch);
                if (!oNextData.bIsFile && !(oNextBranch.folder === FOLDER_EMPTY) && !(oNextBranch.folder === FOLDER_IS_HIDE_IN)) {
                    await ListDirForExplorerRequest(sPath, aJobPath, oBDE, oLDP);
                }
                else {
                    oBDE.DTP.ShowMarkRowInCenter();
                }
            }
            else {
                ErrorMsgShow(GetLocaleText("Err_SmthgWntWrongWthListDirReq"));
            }
        }
        else {
            await TableRowClick(oBDE.DTP, oBDE.Branch, true);
            oBDE.DTP.ShowMarkRowInCenter();
        }
        return;
    }
    const oData = oBDE.Branch.fGetData();
    if (!oData.__oAbort__) {
        oData.__oAbort__ = new AbortController();
    }
    let sTmpPath = sPath;
    if (oData.oBookmark && !oData.bIgnoreBookmark) {
        if (!oData.sFsHandleEnc) {
            await ConnectFsRequest(oData.oConn, aJobPath, oBDE, { oBM: oData.oBookmark }, oLDP.bDontOpen);
            return;
        }
        else {
            sTmpPath = "";
        }
    }
    if (oData.__oAbort__.signal.aborted) {
        oBDE.Branch.fClear();
        return;
    }
    ShowWaitingTimer("Getting Dir list", oBDE, { bDontOpen: oLDP.bDontOpen });
    const oParams = { "path": sTmpPath, "max_items": LIST_DIR_MAX_ITEM };
    try {
        const oListDirData = await ListDirRequestWithReconnect(oParams, { oMultiPageArrs: { items: [] }, abort: oData.__oAbort__ }, oBDE);
        if (sLocPathName === '/web-ui/static/WebGSExplorer.html' && oData.bCanCreateFolder === undefined) {
            if (oData.bAccReadOnly || oData.bContServList) {
                oData.bCanCreateFolder = false;
            }
            else if (oData.bIsServer || !!oData.sAccKey) {
                await FolderInfoRequestForExplorer(oParams.filesys_handle, oBDE, oData);
            }
        }
        await ListDirForExplorerResponseProcessing(oListDirData.items, sPath, aJobPath, oBDE, oLDP);
    }
    catch (oErr) {
        if (oErr && oErr.error && oErr.error.data) {
            oBDE.Branch.oTdProperties = {};
            for (const oTebleCol of oBDE.DTP.aHead) {
                oBDE.Branch.oTdProperties[oTebleCol.field_name] = "err_in_light_bg";
            }
            if (oData.icon == "folder-enc" || oData.icon == "folder-prob-enc") {
                oData.icon = "folder-err-enc";
            }
            else if (oData.icon == "gs-zip" || oData.icon == "gs-prob-zip") {
                oData.icon = "gs-err-zip";
            }
            else if (oData.icon == "account-enc" || oData.icon == "account-prob-enc") {
                oData.icon = "account-err-enc";
            }
            else if (oData.icon == "account-zip" || oData.icon == "account-prob-zip") {
                oData.icon = "account-err-zip";
            }
            AddErrorToTree(oErr.error, oBDE);
            SetDomDisplayAndInnerHtml(oBDE.domErr, "", { text: oErr.error.message + ": " + sPath, class: "job_errors", img: "error" });
        }
        else {
            SendRecivePostApiCatch(oErr, "ListDir err: ", oBDE);
        }
    }
}
async function ListDirForExplorerResponseProcessing(aFolders, sPath, aJobPath, oBDE, oLDP) {
    if (!oBDE.Branch || !oBDE.DTP)
        return;
    oBDE.Branch.fClear();
    oBDE.Branch.oTdProperties = {};
    let oData = oBDE.Branch.fGetData();
    if (oData.icon == "folder-err-enc") {
        oData.icon = "folder-enc";
    }
    else if (oData.icon == "gs-err-zip") {
        oData.icon = "gs-zip";
    }
    else if (oData.icon == "account-err-enc") {
        oData.icon = "account-enc";
    }
    else if (oData.icon == "account-err-zip") {
        oData.icon = "account-zip";
    }
    if (aFolders.length === 0 && (!aJobPath || aJobPath.length === 0)) {
        oBDE.Branch.folder = FOLDER_EMPTY;
        oBDE.DTP.ShowTable();
        if (oLDP.dNeedBranchInfo) {
            await SetBeJobSideAbility(oData, oBDE);
        }
        else if (aJobPath && aJobPath.length === 0) {
            await TableRowClick(oBDE.DTP, oBDE.Branch, true);
        }
        return;
    }
    const oFolderData = SetBrowsTreeFolders(aFolders, sPath, oBDE.Branch, ["_gsdata_"], !!(oBDE.DTP.fFiltr));
    if (oFolderData.aData.length === 0 && (!aJobPath || aJobPath.length === 0)) {
        oBDE.Branch.folder = FOLDER_IS_HIDE_IN;
        oBDE.DTP.ShowTable();
        if (oLDP.dNeedBranchInfo) {
            await SetBeJobSideAbility(oData, oBDE);
        }
        else if (aJobPath && aJobPath.length === 0) {
            await TableRowClick(oBDE.DTP, oBDE.Branch, true);
        }
        return;
    }
    oBDE.DTP.ShowTable();
    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 = {};
    }
    const bNoFolderOnlyFiles = oSavedData.IsWinMode() && oFolderData.nFolderCnt === 0;
    if (bNoFolderOnlyFiles) {
        oData.icon = "folder_with_files";
    }
    if (oLDP.bDontOpen) {
        if (bNoFolderOnlyFiles) {
            oBDE.Branch.folder = FOLDER_NO_FLDR_IN;
            oBDE.DTP.ShowTable();
        }
        return;
    }
    if (oLDP.dNeedBranchInfo) {
        await SetBeJobSideAbility(oData, oBDE);
        return;
    }
    if (aJobPath && aJobPath.length === 0 && oBDE.DTP.oFolderContTable) {
        oBDE.Branch.folder = bNoFolderOnlyFiles ? FOLDER_NO_FLDR_IN : FOLDER_CLOSE;
        oBDE.DTP.ShowTable();
        TableRowClick(oBDE.DTP, oBDE.Branch, true);
        return;
    }
    oBDE.Branch.folder = bNoFolderOnlyFiles ? FOLDER_NO_FLDR_IN : FOLDER_OPEN;
    oBDE.DTP.ShowTableWithOpenFolder(oBDE.Branch);
    ShowFreeSpace(oBDE.DTP);
    if (oLDP.sNameForMark) {
        const oEl = oBDE.Branch.fFindEl(oLDP.sNameForMark);
        if (oEl) {
            oBDE.DTP.MarkTabRow("display_name", oLDP.sNameForMark, oBDE.Branch);
        }
        else {
            await MakeFolderRequest(sPath + "/" + oLDP.sNameForMark, oBDE, oLDP.sNameForMark);
        }
    }
    if (aJobPath === null) {
        return;
    }
    if (!oTargetBranch && aJobPath.length > 0 && aJobPath[0]) {
        await TableRowClick(oBDE.DTP, oBDE.Branch, true);
        oTargetBranch = CreateFakeDir(oBDE, sPath, aJobPath[0]);
    }
    if (oTargetBranch) {
        oTargetBranch.fMarkAndShow(oBDE.DTP);
        oData = oTargetBranch.fGetData();
        oBDE.Branch = oTargetBranch;
        if (aJobPath.length > 0 && aJobPath[0] && !oData.bIsFile) {
            sPath += "/" + aJobPath[0];
            aJobPath.splice(0, 1);
            const sfPathAndName = oData.sHomePath ? oData.oConn.sUrlA + oData.sHomePath : oData.oConn.sUrlA + oData.fGetPathAndName(oTargetBranch);
            const oBm = GetBookmarkInFolder(sfPathAndName, oTargetBranch);
            if (oBm) {
                await ConnectFsRequest(oBm.conn, aJobPath, oBDE, { oBM: oBm.bm });
            }
            else {
                oLDP.bDontOpen = false;
                await ListDirForExplorerRequest(sPath, aJobPath, oBDE, oLDP);
            }
        }
        else if (oData.bIsFile) {
            if (oBDE.DTP.oFolderContTable) {
                oTargetBranch = oTargetBranch.pParent;
                oTargetBranch.fMarkAndShow(oBDE.DTP);
                await TableRowClick(oBDE.DTP, oTargetBranch, true);
                if (oBDE.DTP.oFolderContTable.root.cont) {
                    const oFile = oBDE.DTP.oFolderContTable.root.cont.find(it => it.fGetData().display_name === oData.display_name);
                    if (oFile) {
                        oFile.fMarkAndShow(oBDE.DTP.oFolderContTable);
                        TableRowClick(oBDE.DTP.oFolderContTable, oFile);
                    }
                }
            }
            else {
                await TableRowClick(oBDE.DTP, oTargetBranch, true);
            }
        }
        else {
            await SetBeJobSideAbility(oData, oBDE);
        }
    }
    else if (oData.bIsFile) {
        await TableRowClick(oBDE.DTP, oBDE.Branch, true);
    }
    else {
        await SetBeJobSideAbility(oData, oBDE);
    }
}
function CreateFakeDir(oBDE, sPath, sName) {
    const oTmpFolder = { bIsFolder: true, sDisplayName: sName, sNameA: sName, size: "0" };
    const oTargetBranch = AddNewFolder(oBDE, sPath, sName, oTmpFolder, { display_name: "light_grey_text", comment: "light_grey_text" });
    oBDE.DTP.ShowTable();
    return oTargetBranch;
}
function AddNewFolder(oBDE, sPath, sName, oTmpFolder, oTdProperties) {
    const oTmpFolderData = SetBrowsTreeFolders([oTmpFolder], sPath, oBDE.Branch, []);
    const oTargetBranch = oBDE.Branch.fAddDataArr(oTmpFolderData.aData, {
        oFunc: oTmpFolderData.aFunc,
        fDataProcessor: ProcessFolderBranchForTable,
        "sPathFieldName": "sName",
        "sSpecValue": sName,
        "sFieldNameOfSpecValue": "sName",
        oTdProperties
    });
    return oTargetBranch;
}
function ListDirRequestCatch(err, oBDE) {
    if (err.name == "TypeError") {
        err.message = "Disconnect";
    }
    SendRecivePostApiCatch(err, "ListDir err: ", oBDE);
}
async function BrowsDialogAccountInfoRequest(oBDE, bClone) {
    if (!oBDE || !oBDE.Branch || !oBDE.DTP)
        return;
    let oBr = oBDE.Branch;
    if (oBDE.DTP.oParentBr && oBDE.DTP.oParentDTP) {
        const sName = oBr.fGetData().display_name;
        if (!sName)
            return;
        oBr = oBDE.DTP.oParentBr.fFindEl(sName, "display_name");
        if (!oBr)
            return;
    }
    const oData = oBr.fGetData();
    if (!oData || !oData.sAccKey)
        return;
    try {
        const oAns = await SendRecivePostApiWithRetry("ListAccounts", { "start_from": oData.sAccKey, "max_items": 1 });
        if (oAns.accounts && oAns.accounts.length == 1) {
            ShowAccount(GetFieldValWithDrillUp(oBr, "sFs"), oAns.accounts[0], oBDE, bClone);
        }
        else {
            ErrorMsgShow(GetLocaleText("Err_SmthgWntWrong"));
        }
    }
    catch (oErr) {
        CatchErrProcess(oErr, "", { bNoCurrJobName: true });
    }
}
async function BrowsDialogServerInfoRequest(oBDE) {
    if (!oBDE || !oBDE.Branch)
        return;
    const oData = oBDE.Branch.fGetData();
    const jsInfo = { name: oData.display_name, Type: "Server", Location: oData.sUrl, Comment: oData.comment };
    HtmlMsgbox(JsonToStrAsTree(jsInfo, "<br>", "", 1, true), "Title_ServerProperties", { bNoCurrJobName: true, w_s: "nowrap", lineHeight: "2", nWidth: 600 });
}
async function BrowsDialogInfoRequest(oBDE) {
    if (oBDE && oBDE.Branch) {
        let oData = oBDE.Branch.fGetData();
        let oBr = oBDE.Branch;
        let bWinStyle = false;
        if (oBDE.DTP && oBDE.DTP.oParentBr && oBDE.DTP.oParentDTP) {
            oBr = oBDE.DTP.oParentBr.fFindEl(oData.display_name, "display_name");
            if (!oBr)
                return;
            oData = oBr.fGetData();
            oBDE.DTP = oBDE.DTP.oParentDTP;
            oBDE.Branch = oBr;
            bWinStyle = true;
        }
        let sPath = "";
        if (oData.bIsFile) {
            sPath = oBr.pParent.fGetData().oConn.sUrlA + oData.fGetPathAndName(oBr, true);
        }
        else {
            sPath = oData.oConn.sUrlA + oData.fGetPathAndName(oBr, true);
        }
        try {
            const oAnswer = await GetFolderInfoWithEnc(oData, oBDE, bWinStyle);
            if (!oAnswer)
                return;
            const sHtml = FolderAndFileInfoProcessing(oAnswer, sPath, oData.display_name);
            HtmlMsgbox(sHtml, "Title_FolderProperties", { bNoCurrJobName: true, nWidth: 600, icon: "info" });
        }
        catch { }
    }
}
async function DeleteGroupRequest(sGroupName) {
    try {
        await SendRecivePostApiWithRetry("DeleteGroup", { "group_name": sGroupName });
        await ListGroupRequest("");
        glob.MarkJobInJobList(true);
    }
    catch (oErr) {
        CatchErrProcess(oErr);
    }
}
async function AddJobToGroupRequest(sJobName, sGroupName) {
    try {
        await SendRecivePostApiWithRetry("AddJobToGroup", { "job_name": sJobName, "group_name": sGroupName });
    }
    catch (oErr) {
        CatchErrProcess(oErr);
    }
}
async function DelJobFromGroupRequest(sJobName, sGroupName) {
    try {
        await SendRecivePostApiWithRetry("RemoveJobFromGroup", { "job_name": sJobName, "group_name": sGroupName });
        await ListGroupRequest(sGroupName);
    }
    catch (oErr) {
        CatchErrProcess(oErr);
    }
}
async function DeleteJobRequest(sJobName, bRequireErr) {
    sDeletedJob = sJobName;
    try {
        await SendRecivePostApiWithRetry("DeleteJob", { "job_name": sJobName });
        DeleteJobFromTables([sJobName]);
    }
    catch (oErr) {
        sDeletedJob = "";
        if (bRequireErr) {
            throw oErr;
        }
        CatchErrProcess(oErr);
    }
}
async function StopRequest(sJobName, bForse, bWaitRealStop) {
    const params = { "job_name": sJobName };
    if (bForse) {
        params.force = true;
    }
    try {
        let oJobInList = glob.GetJobInList(sJobName);
        if (oJobInList && oJobInList.stop_forsed) {
            return;
        }
        if (await SendRecivePostApiWithRetry("StopJob", params) === null) {
            return;
        }
        if (oJobInList) {
            if (GetJobIcon(oJobInList) != "stop16") {
                oJobInList.stop_go = true;
            }
            if (bForse) {
                oJobInList.stop_forsed = true;
                while (IsJobActive(sJobName) && bWaitRealStop) {
                    await new Promise(resolve => setTimeout(resolve, 100));
                }
            }
        }
    }
    catch (oErr) {
        CatchErrProcess(oErr);
    }
}
async function CreateAccountRequest(oConn, sHomePath, oBDE, oPar = {}) {
    if (oPar.jsAccData) {
        if (oPar.jsAccData.DisplayName == GetLocaleText("Str_Empty")) {
            oPar.jsAccData.DisplayName = "";
        }
        try {
            if (oPar.bClone) {
                const acc1 = { "sHomePath": oPar.jsAccData.HomePath, "conn": oPar.jsAccData.AcctConn };
                const sAccNames = [];
                for (const oAcc of oBDE.Branch.pParent.jsBody) {
                    if (CompareAcc(acc1, oAcc) === 0) {
                        HtmlErrBox(GetLocaleText("Str_Msg_CannotCreateAccount", [oAcc.display_name]), GetLocaleText("Title_Error"), { bNoCurrJobName: true });
                        if (oPar.oMenu) {
                            ChangeWaitBox("test_results_" + oPar.oMenu.id);
                            SetDomDisplayAndInnerHtml("save_btn_" + oPar.oMenu.id, null, { bEnable: true, text: null });
                        }
                        return;
                    }
                    if (oAcc.display_name) {
                        sAccNames.push(oAcc.display_name);
                    }
                    else {
                        sAccNames.push(GetSummary(oAcc.oConn) + oAcc.sHomePath);
                    }
                }
                const sNewName = GetSummary(oPar.jsAccData.AcctConn) + oPar.jsAccData.HomePath;
                const sUnicname = GetUniqueString(sNewName, sAccNames);
                const jsData = await SendRecivePostApiWithRetry("AddNewAccount", { "account_data": oPar.jsAccData });
                if (sUnicname !== sNewName) {
                    const oRenAccAns = await SendRecivePostApiWithRetry("RenameAccount", { "Key": jsData.account_data.Key, "DisplayName": sUnicname });
                    jsData.account_data.DisplayName = oRenAccAns.DisplayName;
                }
                const aAccounts = SetBrowsTreeAccounts([jsData.account_data], jsData.account_data.hint.list_servers);
                const oNewBr = oBDE.Branch.fAddDatToParent(aAccounts[0], { fDataProcessor: ProcessAccBranchForTable, sPathFieldName: "sAccKey" });
                oBDE.DTP.ShowTable();
                if (oNewBr) {
                    TableRowClick(oBDE.DTP, oNewBr);
                    TableOpenFolder(oBDE.DTP, oNewBr);
                    oNewBr.fMarkAndShow(oBDE.DTP);
                }
            }
            else {
                const oAccData = await SendRecivePostApiWithRetry("UpdateAccount", { "account_data": oPar.jsAccData });
                const oData = oBDE.Branch.fGetData();
                SetSameObjFields(oAccData.account_data.AcctConn, oData.oConn);
                oBDE.Branch.fClear();
                oBDE.Branch.fChangeAllData(oAccData.account_data, SetAccFields);
                RefreshBrowseBranch("", oBDE);
            }
        }
        catch (oErr) {
            CatchErrProcess(oErr);
        }
        CloseFloatMenu(oPar.oMenu);
    }
    else {
        try {
            const jsData = await SendRecivePostApiWithRetry("AddNewAccount", { "account_data": { "AcctConn": oConn, "HomePath": sHomePath } });
            CloseFloatMenu(oPar.oMenu);
            const oBranch = oBDE.Branch;
            jsData.account_data.AcctConn.sUrlA = AddFillUrlForGSTx(jsData.account_data.AcctConn);
            if (oBranch.folder != FOLDER_OPEN) {
                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.fAddDataArr(aAccounts, { fDataProcessor: ProcessAccBranchForTable, sPathFieldName: "sAccKey" });
                oBDE.DTP.ShowTable();
                const oNewBr = oBDE.DTP.MarkTabRow("sAccKey", jsData.account_data.Key, oBranch);
                if (oNewBr && oNewBr.fOpenFolder) {
                    await oNewBr.fOpenFolder(oNewBr, oBDE.DTP);
                }
            }
        }
        catch (oErr) {
            CloseFloatMenu(oPar.oMenu);
            if (oBDE.DTP) {
                oBDE.DTP.ShowTable();
            }
            CatchErrProcess(oErr);
        }
    }
}
async function ListGroupRequest(sGroupName) {
    try {
        aGlobGroup = (await SendRecivePostApiWithRetry("ListGroups", {})).groups;
        const nAllJobsInd = aGlobGroup.findIndex(it => it.m_eGroupType == 1);
        if (nAllJobsInd >= 0) {
            sAllJobsGroupName = aGlobGroup[nAllJobsInd].m_sGroupName;
            aGlobGroup.splice(nAllJobsInd, 1);
        }
        glob.AddGroupToTable(sGroupName);
    }
    catch (oErr) {
        if (oErr) {
            CatchErrProcess(oErr, "", { sErrType: "ListGroups " + oErr.src + ":", eGoal: "console" });
        }
    }
}
async function GetAbout() {
    try {
        const oData = await SendRecivePostApiWithRetry("GetAboutInfo", {});
        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: "img1", title: "", value: "About", h: 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: oData.copyright },
                                        { 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(() => { });
    }
    catch (oErr) {
        CatchErrProcess(oErr, "ListGroups request fail: ", { eGoal: "console" });
    }
}
async function AccountSyncRequest() {
    try {
        await SendRecivePostApiWithRetry("RequestAccountSync", {});
    }
    catch (oErr) {
        CatchErrProcess(oErr, "", { sErrType: "RequestAccountSync:" });
    }
}
async function AccountSyncAuto(bSet) {
    try {
        let sConfText = GetLocaleText("Str_ServerAcctJobSync_Ask_Off");
        if (bSet) {
            sConfText = GetLocaleText("Str_ServerAcctJobSync_Ask_On");
        }
        await AsyncHtmlConfirm(sConfText, "GoodSync", eMyConfDefBtn.ok, { icon: "About", nWidth: 600, bNoCurrJobName: true });
        const oAns = await SendRecivePostApiWithRetry("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) {
        CatchErrProcess(oErr, "", { sErrType: "RequestAccountSync:" });
    }
}
async function AccountSyncAutoRequest() {
    try {
        const oAns = await SendRecivePostApiWithRetry("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) {
        CatchErrProcess(oErr, "", { sErrType: "RequestAccountSync:" });
    }
}
async function OpenFileRequest(sFsHandle, sPath) {
    try {
        return await SendRecivePostApiWithRetry("OpenDownload", { "filesys_handle": sFsHandle, "path": sPath });
    }
    catch (err) {
        throw err;
    }
}
async function DownloadFleBufRequest(sFsHandle, nBufSize) {
    try {
        return await SendRecivePostApiWithRetry("DownloadBuf", { "filesys_handle": sFsHandle, "size": nBufSize });
    }
    catch (err) {
        throw err;
    }
}
async function CloseFileRequest(sFsHandle, bCommit = false) {
    try {
        return await SendRecivePostApiWithRetry("CloseDownload", { "filesys_handle": sFsHandle, "commit": bCommit });
    }
    catch { }
}
async function AsyncDownloadFile(sFsHandle, sPath) {
    try {
        const oFileOpenData = await SendRecivePostApiWithRetry("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 = await SendRecivePostApiWithRetry("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;
        }
        SendRecivePostApiWithRetry("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;
    }
}
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("=======================================================================================");
}
async function LinkToServerOptions() {
    try {
        const GsServerPreAuth = await SendRecivePostApiWithRetry("GetGsServerPreAuth", {});
        window.open(location.protocol + "\/\/" + location.hostname + ":11000" + GsServerPreAuth.preauth_uri, "_blank");
    }
    catch (oErr) {
        if (oErr && oErr.error) {
            ErrorMsgShow(oErr.error.message, { sTitle: "RequestAccountSync " + oErr.src + ":" });
        }
        else {
            ErrorMsgShow(JSON.stringify(oErr), { sTitle: "RequestAccountSync unknown error" });
        }
    }
}
