"use strict";
function SetPercentOfSync(oBrCont, oFileSyncInfo) {
    const nCurr = +oFileSyncInfo.curr;
    const nTotal = +oFileSyncInfo.total;
    if (isNaN(nCurr) || isNaN(nTotal) || nTotal == 0)
        return;
    const oData = oBrCont.fGetData();
    const percent = Math.round(nCurr * 100 / nTotal);
    const signOfAct = SignOfAction({ user_action: oData.user_act, sys_action: oData.sys_act });
    if (signOfAct === -1) {
        oData["lsize"] = percent + "%";
    }
    else if (signOfAct === 1) {
        oData["rsize"] = percent + "%";
    }
    return oData;
}
function SetFieldsAndClassesOfJobTree(oResult) {
    let oTmp = { "name": oResult.name, __class__: {} };
    if (!oResult.data || !oResult.data.lcur || !oResult.data.rcur) {
        oTmp["ldate"] = "[error]";
        oTmp.__class__.ldate = "red";
        return oTmp;
    }
    oTmp.sys_act = oResult.data.sys_action;
    oTmp.user_act = oResult.data.user_action;
    oTmp.state = oResult.data.state;
    oTmp.lcur = {};
    SetNotEmptyObjFieldsFromAnotherObj(oResult.data.lcur, oTmp.lcur);
    oTmp.lold = {};
    SetNotEmptyObjFieldsFromAnotherObj(oResult.data.lold, oTmp.lold);
    oTmp.rcur = {};
    SetNotEmptyObjFieldsFromAnotherObj(oResult.data.rcur, oTmp.rcur);
    oTmp.rold = {};
    SetNotEmptyObjFieldsFromAnotherObj(oResult.data.rold, oTmp.rold);
    let oLinfo = FillLRDateItem(oResult.data.lcur);
    let oRinfo = FillLRDateItem(oResult.data.rcur);
    oTmp["ldate"] = oLinfo.text;
    oTmp["rdate"] = oRinfo.text;
    oTmp["job_icon"] = GetItemType(oResult);
    GetIconIdx(oResult.data, oTmp);
    if (oResult.job_node) {
        oTmp.status = oResult.changes ? GetLocaleText("Cmd_ShowChanges") : "";
        oTmp.__class__.name = "bold_text";
        oTmp.__class__.ldate = "bold_text";
        oTmp.__class__.lsize = "bold_text";
        oTmp.__class__.rdate = "bold_text";
        oTmp.__class__.rsize = "bold_text";
    }
    else {
        oTmp.status = GetJobStatusForTree(oResult.data);
        if (oLinfo.bold || oRinfo.bold) {
            oTmp.__class__.name = "bold_text";
        }
        if (oLinfo.bold) {
            oTmp.__class__.ldate = "bold_text";
            oTmp.__class__.lsize = "bold_text";
        }
        if (oRinfo.bold) {
            oTmp.__class__.rdate = "bold_text";
            oTmp.__class__.rsize = "bold_text";
        }
    }
    if (oTmp.c == "C_Ena_Que_Fil") {
        oTmp.__class__.name = ((oTmp.__class__.name) ? oTmp.__class__.name + " " : "") + "red_text";
    }
    if (oRinfo.not_exists) {
        oTmp.__class__.rdate = ((oTmp.__class__.rdate) ? oTmp.__class__.rdate + " " : "") + "light_grey_text";
        oTmp.__class__.rsize = ((oTmp.__class__.rsize) ? oTmp.__class__.rsize + " " : "") + "light_grey_text";
    }
    if (oLinfo.not_exists) {
        oTmp.__class__.ldate = ((oTmp.__class__.ldate) ? oTmp.__class__.ldate + " " : "") + "light_grey_text";
        oTmp.__class__.lsize = ((oTmp.__class__.lsize) ? oTmp.__class__.lsize + " " : "") + "light_grey_text";
    }
    oTmp.bIsFolder = IsJobTreeFolder(oResult);
    oTmp["lsize"] =
        (oLinfo.not_exists) ?
            "(" + GetLocaleText("IDS_not_present") + ")" :
            (oResult.data.lcur.is_folder && oResult.stat && oResult.stat.lsize) ?
                oResult.stat.lsize + "" :
                oResult.data.lcur.size + "";
    oTmp["l_number"] = (oResult.stat && oResult.stat.lcount) ? oResult.stat.lcount + "" : "";
    oTmp["rsize"] =
        (oRinfo.not_exists) ?
            "(" + GetLocaleText("IDS_not_present") + ")" :
            (oResult.data.rcur.is_folder && oResult.stat && oResult.stat.rsize) ?
                oResult.stat.rsize + "" :
                oResult.data.rcur.size + "";
    oTmp["r_number"] = (oResult.stat && oResult.stat.rcount) ? oResult.stat.rcount + "" : "";
    return oTmp;
}
function SignOfAction(oData) {
    if (oData.user_action === undefined || oData.sys_action === undefined)
        return 0;
    let act = oData.user_action;
    if (!act) {
        act = oData.sys_action;
    }
    switch (act) {
        case 65:
        case 66:
        case 67: return 1;
        case 32:
        case 33:
        case 35: return -1;
    }
    return 0;
}
function ErrShowInJobTree(sMsg, sJobName) {
    const window = document.getElementById("job_tree_window");
    if (!window) {
        return;
    }
    window.innerHTML = "";
    const domHugeText = document.getElementById("huge_wait_text_label");
    if (domHugeText) {
        domHugeText.className = "huge_text err_in_light_bg";
        domHugeText.innerHTML = `Job ${sJobName} ${sMsg}`;
    }
    const oJobInList = glob.GetJobInList(sJobName);
    if (!oJobInList) {
        return;
    }
    oJobInList.oJobStatus.job_run_state = 'Error';
    oJobInList.oJobStatus.sErr = sMsg;
}
async function ShowTextIfNoTree(oJobInList, bKeepTreeModeBtnPnl, bGsDataDeleting) {
    if (!oJobInList)
        return;
    delete jsJobsTables[oJobInList.name];
    const window = document.getElementById("job_tree_window");
    if (!window)
        return;
    try {
        if (!bKeepTreeModeBtnPnl) {
            SetDomDisplayAndInnerHtml("idTopOfDomAbove", "none");
        }
        else {
            const TopOfDomAbove = document.getElementById("idTopOfDomAbove");
            if (TopOfDomAbove) {
                TopOfDomAbove.style.borderBottom = "none";
            }
        }
        window.innerHTML = "";
        const domSummInfo = document.getElementById("job_summary");
        const domHugeText = document.getElementById("huge_wait_text_label");
        if (!domHugeText || !domSummInfo) {
            return;
        }
        domSummInfo.style.flex = "1 1 100%";
        domHugeText.className = "huge_text light_grey_text";
        const domPercentNum = document.getElementById("main_progress_bar_box");
        if (domPercentNum) {
            domPercentNum.classList.remove("short_comments");
        }
        if (!oJobInList.oSideCoords) {
            const aJobSideCoords = await JobListWithSmallDataRequest(aJobFieldsForSideCoords, [sCurrJob]);
            if (aJobSideCoords && aJobSideCoords.length === 1 && aJobSideCoords[0].opt) {
                oJobInList.oSideCoords = aJobSideCoords[0].opt.side_coords;
            }
        }
        if (oJobInList.stop_go) {
            domHugeText.innerHTML = GetLocaleText("Str_StopGo");
        }
        else if (bGsDataDeleting) {
            domHugeText.innerHTML = GetLocaleText("JobStatus_GsDataDeleting");
        }
        else if (oJobInList.oJobStatus) {
            switch (oJobInList.oJobStatus.job_run_state) {
                case "not_analyzed":
                    {
                        if (oJobInList.isWaiting == JOB_COMMAND_ANALIZE) {
                            domHugeText.innerHTML = GetLocaleText("str_analysis_request_sent") + "<br/> " +
                                GetLocaleText("str_waiting_for_analyzing") + "<br/><span id='waiting_animation'></span>";
                        }
                        else if (oJobInList.oSideCoords && oJobInList.oSideCoords[0].conn.sUrlA && oJobInList.oSideCoords[1].conn.sUrlA) {
                            domHugeText.innerHTML = GetLocaleText("Hint_Click_Analyze");
                        }
                        else {
                            domHugeText.innerHTML = GetLocaleText("Str_Startup_Str_ChooseLR");
                        }
                    }
                    break;
                case "waiting_for_locks":
                    {
                        if (!domHugeText.innerHTML.startsWith(GetLocaleText("JobStatus_waiting_for_locks"))) {
                            domHugeText.innerHTML = GetLocaleText("JobStatus_waiting_for_locks") + "<br/><span id='waiting_animation'></span>";
                        }
                    }
                    break;
                case "scheduled_to_run":
                    {
                        if (!domHugeText.innerHTML.startsWith(GetLocaleText("JobStatus_scheduled_to_run"))) {
                            domHugeText.innerHTML = GetLocaleText("JobStatus_scheduled_to_run") + "<br/><span id='waiting_animation'></span>";
                        }
                    }
                    break;
                case "analyze_running":
                    {
                        domHugeText.innerHTML = GetLocaleText("JobStatus_AnalyzingWoPercent");
                        SetDomDisplayAndInnerHtml("job_error", "none");
                    }
                    break;
                case "spop_running":
                case "spop_done":
                case "sync_running":
                case "sync_done":
                case "analyze_done":
                    {
                        if (oJobInList.oJobStatus.job_result == RUN_result_term_error) {
                            if (oJobInList.oJobStatus.stopped_by_locks || oJobInList.oJobStatus.stopped_by_bad_state) {
                                const domMsg = SetDomDisplayAndInnerHtml("job_error", "", { text: oJobInList.oJobStatus.sErr, img: "warning", class: "non_term_error_cell" });
                                if (!domMsg)
                                    break;
                                domMsg.innerHTML += "<p>";
                                const domCheckBox = document.createElement("input");
                                domCheckBox.type = "checkbox";
                                domCheckBox.className = "fltmn_checkbox";
                                domCheckBox.id = "OverrideLocksCB";
                                const domLabel = document.createElement("label");
                                domLabel.append(domCheckBox);
                                domLabel.innerHTML += GetLocaleText("Msg_Override_Locks");
                                domMsg.append(domLabel);
                                const cb = document.getElementById("OverrideLocksCB");
                                if (oJobInList.oJobStatus.stopped_by_locks) {
                                    cb.checked = !!oJobInList.bOverrideByLocks;
                                    cb.onchange = () => {
                                        oJobInList.bOverrideByLocks = cb.checked;
                                    };
                                }
                                else {
                                    cb.checked = !!oJobInList.bOverrideByBadState;
                                    cb.onchange = () => {
                                        oJobInList.bOverrideByBadState = cb.checked;
                                    };
                                }
                                domHugeText.innerHTML = GetLocaleText("JobStatus_Locked");
                            }
                            else {
                                SetDomDisplayAndInnerHtml("job_error", "", { text: oJobInList.oJobStatus.sErr, img: "error" });
                                domHugeText.innerHTML = GetLocaleText("JobStatus_ErrorTerm");
                            }
                        }
                        else if (oJobInList.oJobStatus.job_result == RUN_result_user_stop) {
                            domHugeText.innerHTML = GetLocaleText("Str_Analysis_Stopped_By_User");
                            SetDomDisplayAndInnerHtml("job_error", "none");
                        }
                        else if (oJobInList.oJobStatus.sAttentionMsgA) {
                            domHugeText.innerHTML = GetLocaleText(sHintIfNoTree);
                            SetDomDisplayAndInnerHtml("job_error", "", { text: oJobInList.oJobStatus.sAttentionMsgA, img: "warning", class: "non_term_error_cell" });
                        }
                        else {
                            domHugeText.innerHTML = GetLocaleText(sHintIfNoTree);
                            SetDomDisplayAndInnerHtml("job_error", "none");
                        }
                    }
                    break;
                case "not_connected":
                    {
                        domHugeText.innerHTML = GetLocaleText("Str_not_connected");
                    }
                    break;
            }
        }
    }
    catch { }
}
async function ShowTreeIfThisNeeds(sJobName, oDTP, oJobInList) {
    let window = document.getElementById("job_tree_window");
    if (!window || !oDTP || sCurrJob != sJobName)
        return;
    let sHugeText = document.getElementById("huge_wait_text_label");
    if (sHugeText) {
        sHugeText.innerHTML = "";
    }
    const domSummInfo = document.getElementById("job_summary");
    if (domSummInfo) {
        domSummInfo.style.flex = "0 0 1px";
    }
    const domPercentNum = document.getElementById("main_progress_bar_box");
    if (domPercentNum) {
        domPercentNum.classList.add("short_comments");
    }
    if (oJobInList && oJobInList.oJobStatus) {
        if (oJobInList.oJobStatus.job_result == RUN_result_term_error || oJobInList.oJobStatus.job_result == RUN_result_user_stop) {
            const oErr = GetJobStatus(oJobInList.oJobStatus);
            SetDomDisplayAndInnerHtml("job_error", "", { text: oErr.text, class: oErr.class, img: (oJobInList.oJobStatus.job_result == RUN_result_user_stop) ? "warning" : "error" });
        }
        else if (oJobInList.oJobStatus.job_result == RUN_result_nonterm_errors) {
            const oErr = GetJobStatus(oJobInList.oJobStatus);
            if (oJobInList.aTotals && oJobInList.aTotals[2]) {
                const domJobErr = SetDomDisplayAndInnerHtml("job_error", "", { text: GetLocaleText("Str_JobHasConflicts"), img: "warning", class: oErr.class + " flex_gor_left" });
                if (domJobErr) {
                    const domBtnBox = document.createElement("div");
                    if (domBtnBox) {
                        domBtnBox.className = "flex_gor_left";
                        domJobErr.append(domBtnBox);
                        CreateImgButtonBar(jsConflictResolveImgMenu, domBtnBox, { bHorizontalButtons: true, bDontClearContainer: true });
                    }
                }
            }
            else {
                SetDomDisplayAndInnerHtml("job_error", "", { text: oErr.text, class: oErr.class, img: "warning" });
            }
        }
        else if (oJobInList.oJobStatus.sAttentionMsgA) {
            SetDomDisplayAndInnerHtml("job_error", "", { text: oJobInList.oJobStatus.sAttentionMsgA, img: "warning", class: "non_term_error_cell" });
        }
        else if (oJobInList.aTotals) {
            if (oJobInList.aTotals[3]) {
                SetDomDisplayAndInnerHtml("job_error", "", { text: GetLocaleText("Err_AnalyzeFinishedWithErrors"), class: "job_errors flex_gor_center", img: "warning" });
            }
            else if (oJobInList.aTotals[2]) {
                const domJobErr = SetDomDisplayAndInnerHtml("job_error", "", { text: GetLocaleText("Str_JobHasConflicts"), class: "attent_cell flex_gor_center", img: "warning" });
                if (domJobErr) {
                    const domBtnBox = document.createElement("div");
                    if (domBtnBox) {
                        domBtnBox.className = "flex_gor_left";
                        domJobErr.append(domBtnBox);
                        CreateImgButtonBar(jsConflictResolveImgMenu, domBtnBox, { bHorizontalButtons: true, bDontClearContainer: true });
                    }
                }
            }
            else {
                SetDomDisplayAndInnerHtml("job_error", "none");
            }
        }
    }
    else {
        SetDomDisplayAndInnerHtml("job_error", "none");
    }
    if (oDTP.domLimWindow == window) {
        if (oDTP.domBody) {
            await oDTP.ShowTable();
        }
        else {
            await oDTP.CreateListElements();
        }
    }
    else {
        oDTP.domLimWindow = window;
        await CreateTable(oDTP);
    }
    if (oDTP.aDeploedTable.length == 0) {
        if (oJobInList && oJobInList.oJobStatus && oJobInList.oJobStatus.job_result != RUN_result_term_error) {
            CreatePanelOfJobModeView(oJobInList.aTotals, glob.GetTreeMode(sJobName));
        }
        return;
    }
}
function SetNoTree(dom) {
    if (!dom)
        return;
    dom.innerHTML = "";
    dom.className = "flex_vert height100";
    const domNoTree1 = document.createElement("div");
    domNoTree1.className = "flex_1_1_100";
    dom.append(domNoTree1);
    const textNoTree = document.createElement("div");
    dom.append(textNoTree);
    textNoTree.className = "huge_text light_grey_text";
    textNoTree.innerHTML = GetLocaleText(sHintIfNoTree);
    const domNoTree2 = document.createElement("div");
    domNoTree2.className = "flex_1_1_100";
    dom.append(domNoTree2);
}
function SetFoldAndClass(oBrCont, data) {
    const oData = SetFieldsAndClassesOfJobTree(data);
    for (let key of Object.keys(oData.__class__)) {
        if (oData.__class__[key]) {
            oData.__class__[key] = oData.__class__[key].trim();
        }
        else {
            delete oData.__class__[key];
        }
    }
    if (Object.keys(oData.__class__).length > 0) {
        oBrCont.oTdProperties = oData.__class__;
    }
    if (oData.bIsFolder) {
        if (!oBrCont.cont) {
            oBrCont.cont = [];
        }
        if (!data.stat) {
            const oOldData = oBrCont.fGetData();
            if (oOldData) {
                oData.lsize = oOldData.lsize || "";
                oData.rsize = oOldData.rsize || "";
                oData.l_number = oOldData.l_number || "";
                oData.r_number = oOldData.r_number || "";
            }
        }
    }
    if (oData.bDeadRow) {
        oBrCont.bDeadRow = true;
    }
    return oData;
}
function GetBranchProperty(oBranch, bIsFolder, oBranchPropertys) {
    oBranchPropertys["right_is"] = !isNaN(+(oBranch.rsize + ""));
    oBranchPropertys["left_is"] = !isNaN(+(oBranch.lsize + ""));
    oBranchPropertys["diff_time"] = (oBranch.rdate != oBranch.ldate) && (oBranch.cksum == oBranch.cksum) && (oBranch.rsize == oBranch.lsize);
    oBranchPropertys["diff_reg"] = (oBranch.rdate == oBranch.ldate) && (oBranch.cksum == oBranch.cksum) && (oBranch.rsize == oBranch.lsize);
    oBranchPropertys["equal"] = bIsFolder ? (oBranch.l_number === "" && oBranch.r_number === "") : (oBranch.c == "C_Ena_Fill");
}
function JobTreeRightButtonFunc(e, oBranch, oDTP) {
    DeleteAllDropMenu();
    let aPaths = [];
    for (let i = 0; i < oDTP.fGetSelTabLen(); i++) {
        aPaths.push(oDTP.fGetSelBranch(i).fGetPathStr("/"));
    }
    let oBranchPropertys = { "path_arr": aPaths, "oTreeRow": oDTP.aDeploedTable[oBranch.dep_ind] };
    if (aPaths.length == 1) {
        let bIsFolder = "folder" in oBranch;
        GetBranchProperty(oBranch.fGetData(), bIsFolder, oBranchPropertys);
        if (bIsFolder) {
            CreateDropMenuItems(jsUserActsMenu.folder, e.clientX, e.clientY, e.clientX, e.target, false, oBranchPropertys);
        }
        else {
            CreateDropMenuItems(jsUserActsMenu.file, e.clientX, e.clientY, e.clientX, e.target, false, oBranchPropertys);
        }
    }
    else {
        CreateDropMenuItems(jsUserActsMenu.multy, e.clientX, e.clientY, e.clientX, e.target, false, oBranchPropertys);
    }
}
function GetHintUserActButton(sFieldName, oBranch) {
    if (!oBranch) {
        return "";
    }
    if (sFieldName == "c") {
        return "Cmd_DoNotCopy";
    }
    if (oBranch.job_icon == "folder" || oBranch.job_icon == "job") {
        return (sFieldName == "l") ? "Cmd_CopyRightToLeft" : (sFieldName == "r") ? "Cmd_CopyLeftToRight" : "Cmd_DoNotCopy";
    }
    let oBranchPropertys = { path_arr: [] };
    GetBranchProperty(oBranch, false, oBranchPropertys);
    if (oBranchPropertys.diff_reg) {
        return (sFieldName == "l") ? "Cmd_NameCaseRightToLeft" : "Cmd_NameCaseLeftToRight";
    }
    if (oBranchPropertys.diff_time) {
        if (sFieldName == "l") {
            if (oBranch.l == "L_Ena_Arr_Fil" || oBranch.l == "L_Ena_Arr_Nofl" || oBranch.r == "R_Ena_Ts_Nofl") {
                return "Cmd_CopyTimeRightToLeft";
            }
            else {
                return "Cmd_CopyRightToLeft";
            }
        }
        else {
            if (oBranch.r == "R_Ena_Arr_Fill" || oBranch.r == "R_Ena_Arr_Nofl" || oBranch.l == "L_Ena_Ts_Nofl") {
                return "Cmd_CopyTimeLeftToRight";
            }
            else {
                return "Cmd_CopyLeftToRight";
            }
        }
    }
    return (sFieldName == "l") ? "Cmd_CopyRightToLeft" : (sFieldName == "r") ? "Cmd_CopyLeftToRight" : "Cmd_DoNotCopy";
}
function UserActButton(sFieldName, oBranch) {
    let aPaths = [];
    if (oBranch._branch_.pathEl) {
        aPaths.push(oBranch._branch_.fGetPathStr("/"));
    }
    SpOpRequest2(GetHintUserActButton(sFieldName, oBranch._branch_.fGetData()), aPaths);
}
function GetItemPath(oArgs) {
    return "\/" + oArgs.path_arr[0];
}
function GetOnlyName(s) {
    return s.slice(s.lastIndexOf("/") + 1);
}
function GetItemName(oArgs) {
    return GetOnlyName(oArgs.path_arr[0]);
}
function GetOnlyExtention(s) {
    let nDotPos = s.lastIndexOf(".");
    if (nDotPos > s.lastIndexOf("/")) {
        return s.slice(nDotPos);
    }
    return "";
}
function GetItemExt(oArgs) {
    return GetOnlyExtention(oArgs.path_arr[0]);
}
function GetItemNumb(aArgs) {
    return aArgs.path_arr.length;
}
function GetSpOp(text) {
    switch (text) {
        case "Cmd_Recommended": return { "sp_op": SpOp_ChangeItemActionHereAndBelow, "user_act": EA_USESYSTEM };
        case "Cmd_DoNotCopy": return { "sp_op": SpOp_ChangeItemActionHereAndBelow, "user_act": EA_NO_COPY };
        case "Cmd_CopyRightToLeft": return { "sp_op": SpOp_ChangeItemActionHereAndBelow, "user_act": EA_COPY_FILE_RTOL };
        case "Cmd_CopyLeftToRight": return { "sp_op": SpOp_ChangeItemActionHereAndBelow, "user_act": EA_COPY_FILE_LTOR };
        case "Cmd_CopyTimeLeftToRight": return { "sp_op": SpOp_ChangeItemActionHereAndBelow, "user_act": EA_COPY_TIME_ATTR_LTOR };
        case "Cmd_CopyTimeRightToLeft": return { "sp_op": SpOp_ChangeItemActionHereAndBelow, "user_act": EA_COPY_TIME_ATTR_RTOL };
        case "Cmd_NameCaseLeftToRight": return { "sp_op": SpOp_ChangeItemActionHereAndBelow, "user_act": EA_COPY_NAME_CASE_LTOR };
        case "Cmd_NameCaseRightToLeft": return { "sp_op": SpOp_ChangeItemActionHereAndBelow, "user_act": EA_COPY_NAME_CASE_RTOL };
        case "Cmd_DeleteLFolder": return { "sp_op": SpOp_DeleteItems_Left, "user_act": -1 };
        case "Cmd_DeleteRFolder": return { "sp_op": SpOp_DeleteItems_Right, "user_act": -1 };
        case "Cmd_DeleteBothFolders": return { "sp_op": SpOp_DeleteItems_Both, "user_act": -1 };
        case "Cmd_ItemLDelete": return { "sp_op": SpOp_DeleteItems_Left, "user_act": -1 };
        case "Cmd_ItemRDelete": return { "sp_op": SpOp_DeleteItems_Right, "user_act": -1 };
        case "Cmd_ItemDeleteBoth": return { "sp_op": SpOp_DeleteItems_Both, "user_act": -1 };
        case "Cmd_ItemLDeleteMul1": return { "sp_op": SpOp_DeleteItems_Left, "user_act": -1 };
        case "Cmd_ItemRDeleteMul1": return { "sp_op": SpOp_DeleteItems_Right, "user_act": -1 };
        case "Cmd_ItemBDeleteMul1": return { "sp_op": SpOp_DeleteItems_Both, "user_act": -1 };
        case "Cmd_ItemExcludeFile1": return { "user_act": FLT_ACT_EXC_PATH };
        case "Cmd_ItemExcludeFolder1": return { "user_act": FLT_ACT_EXC_PATH };
        case "Cmd_ItemExcludeMulti1": return { "user_act": FLT_ACT_EXC_PATH };
        case "Cmd_ItemIncludeFile1": return { "user_act": FLT_ACT_INC_PATH };
        case "Cmd_ItemIncludeFolder1": return { "user_act": FLT_ACT_INC_PATH };
        case "Cmd_ItemIncludeMulti1": return { "user_act": FLT_ACT_INC_PATH };
        case "Cmd_ItemExcludeAllFiles1": return { "user_act": FLT_ACT_EXC_NAME };
        case "Cmd_ItemExcludeAllFolders1": return { "user_act": FLT_ACT_EXC_NAME };
        case "Cmd_ItemExcludeAllMulti1": return { "user_act": FLT_ACT_EXC_NAME };
        case "Cmd_ItemExcludeAllMask1": return { "user_act": FLT_ACT_EXC_MASK };
        case "Cmd_ItemExcludeAllMaskMulti1": return { "user_act": FLT_ACT_EXC_MASK };
        case "Cmd_ItemIncludeAllMask1": return { "user_act": FLT_ACT_INC_MASK };
        case "Cmd_ItemIncludeAllMaskMulti2": return { "user_act": FLT_ACT_INC_MASK };
        case "Cmd_JobResetState": return { "sp_op": SpOp_DeleteStateFiles, "user_act": -1 };
        case "Cmd_JobDeleteBackup": return { "sp_op": SpOp_DeleteRecycledAndHistory, "user_act": -1 };
        case "Cmd_JobDeleteGsData": return { "sp_op": SpOp_DeleteGsData_Both, "user_act": -1 };
        case "Cmd_JobCleanupRecycled": return { "sp_op": SpOp_CleanupRecycled, "user_act": -1 };
        default: return null;
    }
}
function SpOpRequestConfirm(text, aPaths) {
    if (aPaths.path_arr.length < 1) {
        return;
    }
    let s = "";
    if (aPaths.path_arr.length < 4) {
        const args = ["", "", ""];
        for (let i = 0; i < aPaths.path_arr.length; i++) {
            args[i] = aPaths.path_arr[i];
        }
        s = GetLocaleText("Str_AskDeleteItem3", args, { sQuotes: '"', sTermSign: ", ", bBold: true });
    }
    else {
        s = GetLocaleText("Str_AskDeleteItem1", ["" + aPaths.path_arr.length]);
    }
    let sSide = "";
    switch (text) {
        case 'Cmd_ItemLDelete':
        case 'Cmd_DeleteLFolder':
        case 'Cmd_ItemLDeleteMul1':
            sSide = ": left side";
            break;
        case 'Cmd_ItemRDelete':
        case 'Cmd_DeleteRFolder':
        case 'Cmd_ItemRDeleteMul1':
            sSide = ": right side";
            break;
        default: sSide = ": both sides";
    }
    HtmlConfirm(s, sSide, eMyConfDefBtn.cancel, { icon: "C_Ena_Que_Fil" })
        .then(() => SpOpRequest2(text, aPaths.path_arr)).catch(() => { });
}
function MainJobTableProc(oBrCont, data) {
    oBrCont.oTdProperties = data.__class__;
    return data;
}
function GetJobTree() {
    const jobTree = { "name": sAllJobsGroupName, job_icon: "circle-outline", __class__: {} };
    const oFunc = {};
    oFunc.fRowClick = GroupRowClick;
    oFunc.fRightBtn = function (e, Branch, DTP) {
        GroupRowClick(Branch);
        CreateDropMenuItems(jsGroupMenu, e.clientX, e.clientY, e.clientX, e.target, false, { Branch, DTP });
    };
    return { jT: jobTree, oF: oFunc };
}
function StartGroupButton(btn, nCommand) {
    if (!domGroupName.innerHTML || btn.classList.contains("dead_btn"))
        return;
    if (domGroupName.innerHTML == sAllJobsGroupName) {
        if (glob.GetJobArr().length > 0) {
            for (const oJob of glob.GetJobArr()) {
                StartJobWithCheck(oJob.name, nCommand);
            }
        }
    }
    else if (aGlobGroup) {
        const oGroup = aGlobGroup.find(it => it.m_sGroupName == domGroupName.innerHTML);
        if (oGroup) {
            for (const sJobName of oGroup.m_jobsInGroup) {
                StartJobWithCheck(sJobName, nCommand);
            }
        }
    }
}
function StartJobFromDropMenuGroup(nCommand, xAddArgs) {
    let sGroupName;
    if (!xAddArgs) {
        sGroupName = domGroupName.innerHTML;
    }
    else if (typeof xAddArgs === 'string') {
        sGroupName = xAddArgs;
    }
    else if (xAddArgs.Branch) {
        sGroupName = xAddArgs.Branch.pathEl;
    }
    if (!sGroupName)
        return;
    if (sGroupName == sAllJobsGroupName) {
        if (glob.GetJobArr().length > 0) {
            for (const oJob of glob.GetJobArr()) {
                StartJobWithCheck(oJob.name, nCommand);
            }
        }
    }
    else if (aGlobGroup) {
        const oGroup = aGlobGroup.find(it => it.m_sGroupName == sGroupName);
        if (oGroup) {
            for (const sJobName of oGroup.m_jobsInGroup) {
                StartJobWithCheck(sJobName, nCommand);
            }
        }
    }
}
function StopJobFromDropMenuGroup(xAddArgs) {
    let sGroupName;
    if (!xAddArgs) {
        sGroupName = domGroupName.innerHTML;
    }
    else if (typeof xAddArgs === 'string') {
        sGroupName = xAddArgs;
    }
    else if (xAddArgs.Branch) {
        sGroupName = xAddArgs.Branch.pathEl;
    }
    if (!sGroupName)
        return;
    if (sGroupName == sAllJobsGroupName) {
        if (glob.GetJobArr().length > 0) {
            for (const oJob of glob.GetJobArr()) {
                StopOneJob(oJob.name);
            }
        }
    }
    else if (aGlobGroup) {
        const oGroup = aGlobGroup.find(it => it.m_sGroupName == sGroupName);
        if (oGroup) {
            for (const sJobName of oGroup.m_jobsInGroup) {
                StopOneJob(sJobName);
            }
        }
    }
}
function StartJobBigButton(btn, nCommand) {
    if (!sCurrJob || !IsJobReadyToAnalize(sCurrJob) || btn.classList.contains("dead_btn"))
        return;
    StartJobRequest(sCurrJob, nCommand);
}
function StartJobFromDropMenu(nCommand, xAddArgs) {
    if (!xAddArgs) {
        StartJobWithCheck(sCurrJob, nCommand);
    }
    else if (typeof xAddArgs === 'string') {
        StartJobWithCheck(xAddArgs, nCommand);
    }
    else if (xAddArgs.DTP) {
        const nSelTabLen = xAddArgs.DTP.fGetSelTabLen();
        if (nSelTabLen > 0) {
            for (let i = 0; i < nSelTabLen; i++) {
                StartJobWithCheck(xAddArgs.DTP.fGetSelBranch(i).fGetData().name, nCommand);
            }
        }
        else {
            StartJobWithCheck(xAddArgs.Branch.fGetData().name, nCommand);
        }
    }
}
function StartJobWithCheck(sJobName, command) {
    if (!sJobName)
        return;
    if (command == JOB_COMMAND_SYNC && !IsJobReadyToSync(sJobName))
        return;
    if (!IsJobReadyToAnalize(sJobName))
        return;
    StartJobRequest(sJobName, command);
    if (command == JOB_COMMAND_ANALIZE || command == JOB_COMMAND_ANALIZE_AND_SYNC) {
        glob.SetTreeMode(sJobName, DEF_TREE_MODE);
    }
}
function RightJobTableRowClick(oDepBr) {
    ChangeCurrJob(oDepBr.fGetData().name, "");
    FillRightWindow();
}
function RightJobTableRightBtn(e, oBranch, oDTP) {
    const tmpJobMenu = CopyArray(jsJobMenu);
    if (oDTP.fGetSelTabLen() == 1) {
        const sJobName = oBranch.fGetData().name;
        ChangeCurrJob(sJobName, "");
        FillRightWindow();
        const nAddToGroup = tmpJobMenu.findIndex(it => it.title == "Str_AddToGroup");
        if (nAddToGroup >= 0 && tmpJobMenu.length > nAddToGroup + 1 && aGlobGroup) {
            if (oBranch.pParent) {
                const pGroup = aGlobGroup.find(it => it.m_sGroupName == oBranch.pParent.pathEl);
                if (pGroup && pGroup.m_eGroupType == GROUP_TYPE_USER) {
                    delete tmpJobMenu[nAddToGroup + 1]["disable"];
                    tmpJobMenu[nAddToGroup + 1].title = GetLocaleText("Str_RemoveFromGroup", [pGroup.m_sGroupName], { sQuotes: "'" });
                    tmpJobMenu[nAddToGroup + 1].command = "DelJobFromGroupRequest('" + sJobName + "', '" + pGroup.m_sGroupName + "')";
                }
            }
        }
    }
    JobContextMenu(tmpJobMenu, e.clientX, e.clientY, e.clientX, e.target, false, { "Branch": oBranch, "DTP": oDTP });
}
function SetDiskSpaceInfo(oDiskSpaceInfo, sSide) {
    const domDiskSpace = document.getElementById(sSide + "_diagram1");
    if (!domDiskSpace)
        return;
    domDiskSpace.style.display = "";
    const domDiskOccupisedSpace = document.getElementById(sSide + "_diagram_occup1");
    const oDiscSpaces = ConvertBytes(oDiskSpaceInfo.total, oDiskSpaceInfo.available);
    domDiskOccupisedSpace.style.width = ((oDiscSpaces.nSpace1 - oDiscSpaces.nSpace2) * 100 / oDiscSpaces.nSpace1) + "%";
    const oDiscFreeSpaces = ConvertBytes(oDiskSpaceInfo.available);
    let sSpaceInfo = "Total: <span class='neutral_space_text'>" + RoundTo3Digits(oDiscSpaces.nSpace1) + " " + oDiscSpaces.unit + "</span>" +
        ", Free: <span class='neutral_space_text'>" + RoundTo3Digits(oDiscFreeSpaces.nSpace1) + " " + oDiscFreeSpaces.unit + "</span>";
    if (oDiskSpaceInfo.required_for_sync) {
        const oRequirSpaces = ConvertBytes(oDiskSpaceInfo.total, oDiskSpaceInfo.required_for_sync);
        const domDiskRequirSpace = document.getElementById(sSide + "_diagram_recuir1");
        let nRequirProc = oRequirSpaces.nSpace2 * 100 / oRequirSpaces.nSpace1;
        if (nRequirProc > 102) {
            nRequirProc = 102;
        }
        domDiskRequirSpace.style.width = nRequirProc + "%";
        const oRequirSpacesText = ConvertBytes(oDiskSpaceInfo.required_for_sync);
        if (oDiscSpaces.nSpace2 >= oRequirSpaces.nSpace2) {
            domDiskRequirSpace.style.background = "#0a0";
            sSpaceInfo += ", Required for sync: <span class='good_space_text'>" + RoundTo3Digits(oRequirSpacesText.nSpace1) + " " + oRequirSpacesText.unit + "</span>";
        }
        else {
            domDiskRequirSpace.style.background = "red";
            sSpaceInfo += ", Required for sync: <span class='bad_space_text'>" + RoundTo3Digits(oRequirSpacesText.nSpace1) + " " + oRequirSpacesText.unit + "</span>";
        }
    }
    document.getElementById(sSide + "_space").innerHTML = sSpaceInfo;
}
function ChangeJobDirect() {
    if (IsJobActive(sCurrJob))
        return;
    const rect = domJobDirect.getBoundingClientRect();
    CreateDropMenu(jsDirectChangeDropMenu, rect.left, rect.bottom, rect.right, domJobDirect, { class: "middl_drop_menu" });
}
function SetSideDetailsInfo(domSideText, domSideImg, oJobInList, nInd, sUrlL, sUrlR, sDomSideId) {
    if (!domSideText)
        return;
    let sIcon = oJobInList.iconFsL;
    if (nInd) {
        sIcon = oJobInList.iconFsR;
    }
    SetTextAndIconJobDetaleSide(domSideText, domSideImg, oJobInList, nInd, sIcon);
    const domSideDetails = document.getElementById(sDomSideId);
    if (domSideDetails) {
        domSideDetails.onclick = () => {
            if (!oJobInList)
                return;
            CreateBrowsDialogWindows(nInd, oJobInList);
        };
        domSideDetails.oncontextmenu = (e) => {
            e.preventDefault();
            DeleteAllDropMenu();
            CreateDropMenuItems(jsFolderMenu, e.clientX, e.clientY, e.clientX, null, false, { oJobInList, nInd });
        };
        domSideDetails.title = GetPathForShow(oJobInList.oSideCoords[nInd].conn.sUrlA);
    }
}
function SetTextAndIconJobDetaleSide(domSideText, domSideImg, oJobInList, nInd, sIcon) {
    if (!domSideText)
        return;
    domSideText.innerText = GetPathForShow(oJobInList.oSideCoords[nInd].conn.sUrlA);
    domSideText.innerHTML = domSideText.innerText.replaceAll("/", "<span>/</span>");
    if (domSideText.innerHTML) {
        if (domSideImg) {
            domSideImg.classList.remove("unknown_folder_icon");
            domSideImg.classList.add("big_direct_icon");
            if (!sIcon) {
                FileSysWindSettingRequest(domSideImg, oJobInList.oSideCoords[nInd].conn.sUrlA, oJobInList, !nInd);
            }
            else {
                const img = SetImg(sIcon, "var(--job-detale-img-size)", "abs_pos_img");
                domSideImg.innerHTML = "";
                if (img)
                    domSideImg.append(img);
            }
        }
        if (domSideText.parentElement) {
            domSideText.parentElement.style.justifyContent = "";
        }
    }
    else {
        let sText = "";
        const eDir = GetNumberOfJobDirect(oJobInList.direct);
        if (nInd) {
            sText = (eDir == JS_TWO_WAY) ? GetLocaleText("Title_Right_Side") :
                (eDir == JS_LEFT_TO_RIGHT) ? GetLocaleText("Str_DestinFolder") :
                    (eDir == JS_RIGHT_TO_LEFT) ? GetLocaleText("Str_SourceFolder") : GetLocaleText("Help_Browse_Edit");
        }
        else {
            sText = (eDir == JS_TWO_WAY) ? GetLocaleText("Title_Left_Side") :
                (eDir == JS_LEFT_TO_RIGHT) ? GetLocaleText("Str_SourceFolder") :
                    (eDir == JS_RIGHT_TO_LEFT) ? GetLocaleText("Str_DestinFolder") : GetLocaleText("Help_Browse_Edit");
        }
        domSideText.innerHTML = "<div class='flex_vert_center click_to_select_folder'><div>" + sText + "</div><button class='flt_menu_btn'>" + GetLocaleText("Btn_SelectFolder") + "</botton></div>";
        if (domSideText.parentElement) {
            domSideText.parentElement.style.justifyContent = "center";
        }
        if (domSideImg) {
            const img = SetImg("unknown_folder", "var(--job-unknown-folder-size)", "abs_pos_img");
            domSideImg.innerHTML = "";
            if (img) {
                domSideImg.classList.remove("big_direct_icon");
                domSideImg.classList.add("unknown_folder_icon");
                domSideImg.append(img);
            }
        }
    }
    const oOpts = oJobInList.oSideCoords[nInd].opts;
    if (oOpts) {
        let sCompressType = "";
        if (oOpts.nCompressType > 1) {
            sCompressType = GetLocaleText("Str_Deflate");
            if (oOpts.nCipherType > 0) {
                sCompressType += "<br/>" + GetLocaleText("Str_Encrypted") + " (" + ((oOpts.nCipherType === 1) ? GetLocaleText("Str_Side_Cipher_ZipCrypto") : GetLocaleText("Str_Side_Cipher_AES256")) + ")";
            }
        }
        else if (oOpts.bEncryptBodies || oOpts.bEncryptPaths) {
            sCompressType = GetLocaleText("Str_EncFileNames") + "<br/>" + GetLocaleText("Chk_Encrypt_FilePaths");
        }
        if (nInd) {
            if (sCompressType) {
                domRightCryptoInfo.style.display = "";
                domRightCryptoInfo.innerHTML = sCompressType;
            }
            else {
                domRightCryptoInfo.style.display = "none";
            }
        }
        else {
            if (sCompressType) {
                domLeftCryptoInfo.style.display = "";
                domLeftCryptoInfo.innerHTML = sCompressType;
            }
            else {
                domLeftCryptoInfo.style.display = "none";
            }
        }
    }
}
async function RenameJobRequest(sOldName, sNewJobName) {
    bStopListJobStatusesResponseProcessing = true;
    try {
        const sNewName = (await SendRecivePostApiWithRetry("RenameJob", { "job_name": sOldName, "new_job_name": sNewJobName })).new_job_name;
        const oJobInList = glob.GetJobInList(sOldName);
        if (oJobInList) {
            oJobInList.name = sNewName;
        }
        glob.RenameJobInTable(sOldName, sNewName);
        if (sCurrJob === sOldName) {
            ChangeCurrJob(sNewName, "");
        }
    }
    catch (oErr) {
        CatchErrProcess(oErr);
    }
    bStopListJobStatusesResponseProcessing = false;
}
function DeleteJobFromTables(sJobName) {
    let nNextJob = -1;
    for (const it of sJobName) {
        const nJobInList = glob.GetJobArr().findIndex(item => item.name == it);
        if (nJobInList >= 0) {
            glob.GetJobArr().splice(nJobInList, 1);
            nNextJob = nJobInList;
        }
        if (aGlobGroup) {
            for (const aGroup of aGlobGroup) {
                const nJobInGroup = aGroup.m_jobsInGroup.findIndex(item => item == it);
                if (nJobInGroup >= 0) {
                    aGroup.m_jobsInGroup.splice(nJobInGroup, 1);
                }
            }
        }
    }
    sDeletedJob = "";
    glob.DeleteJobFromTable(nNextJob);
    bExtraJobsDetected = false;
}
function AddOrRemoveGroupJob(e, Branch, DTP) {
    if (DTP.fGetSelTabLen() != 1)
        return;
    GroupRowClick(Branch);
    CreateDropMenuItems(jsGroupMenu, e.clientX, e.clientY, e.clientX, e.target, false, { Branch, DTP });
}
function DeleteGroup(xAddArgs) {
    if (!xAddArgs) {
        const oDTP = glob.GetActiveJobTable(true);
        if (!oDTP || oDTP.fGetSelTabLen() !== 1)
            return;
        xAddArgs = oDTP.fGetSelBranch(0).fGetData().name;
    }
    else if (!(typeof xAddArgs === 'string')) {
        xAddArgs = xAddArgs.Branch.fGetData().name;
    }
    HtmlConfirm("<p>" + GetLocaleText("Str_AskDeleteGroup", [xAddArgs]), "", eMyConfDefBtn.ok, { sFontSize: "1.25rem" })
        .then(() => {
        DeleteGroupRequest(xAddArgs);
    }).catch(() => { });
}
function IsUserGroup(xAddArgs) {
    if (!aGlobGroup)
        return false;
    if (!xAddArgs || !(typeof xAddArgs === 'string')) {
        const oDTP = glob.GetActiveJobTable(true);
        if (!oDTP || oDTP.fGetSelTabLen() !== 1)
            return false;
        xAddArgs = oDTP.fGetSelBranch(0).fGetData().name;
    }
    const oGroup = aGlobGroup.find(it => it.m_sGroupName == xAddArgs);
    if (!oGroup || oGroup.m_eGroupType != GROUP_TYPE_USER)
        return false;
    return true;
}
function GroupNameProcessing(oTBC, obj) {
    const oGroup = { job_icon: GetIconForGroup(obj.m_eGroupType, obj.m_sGroupName), name: obj.m_sGroupName, nGroupType: obj.m_eGroupType, tTimeStamp: obj.m_tTimeStamp };
    oTBC.cont = [];
    if (obj.bOpenFolder) {
        oTBC.folder = FOLDER_OPEN;
    }
    else {
        oTBC.folder = FOLDER_CLOSE;
    }
    return oGroup;
}
function GroupJobProcessing(arr, oDTP) {
    const aGroupJob = [];
    for (const it of arr) {
        const oJobBranch = oDTP.fFindBranchArr([sAllJobsGroupName, it]);
        if (!oJobBranch) {
            continue;
        }
        aGroupJob.push({ "name": it, "job_icon": oJobBranch.fGetData().job_icon, "pJobImMainTable": oJobBranch });
    }
    return aGroupJob;
}
async function AddJobToGroup(sGroupName, xAddArgs) {
    if (!xAddArgs) {
        xAddArgs = { DTP: glob.GetActiveJobTable() };
    }
    if (typeof xAddArgs != 'string') {
        const nLen = xAddArgs.DTP.fGetSelTabLen();
        for (let i = 0; i < nLen; i++) {
            await AddJobToGroupRequest(xAddArgs.DTP.fGetSelBranch(i).pathEl, sGroupName);
        }
    }
    else {
        await AddJobToGroupRequest(xAddArgs, sGroupName);
    }
    await ListGroupRequest(sGroupName);
}
async function GroupRowClick(oGroup) {
    if (!glob.IsJobTable() || !oGroup.cont)
        return;
    ChangeCurrJob("", oGroup.pathEl || "");
    glob.ResetJobTable("right");
    if (domGroupName && oGroup.pathEl) {
        domGroupName.innerHTML = oGroup.pathEl;
        domGroupTopMenu.style.display = "";
    }
    const pGroupTable = new CDynTabProp();
    pGroupTable.aHead = jsRightWinowsTableHead;
    pGroupTable.fSaveColsSize = (arr) => {
        for (let i = 0; i < pGroupTable.aTableColsWidth.length; i++) {
            if (arr[i] && arr[i] > 0) {
                pGroupTable.aTableColsWidth[i] = arr[i];
            }
        }
        oSavedData.aRightJobTableColsSize = pGroupTable.aTableColsWidth;
        localStorage.setItem("oSavedData", JSON.stringify(oSavedData));
    };
    pGroupTable.fGetColsSizeFromLocStor = () => {
        if (oSavedData.aRightJobTableColsSize && oSavedData.aRightJobTableColsSize.length) {
            pGroupTable.aTableColsWidth = oSavedData.aRightJobTableColsSize;
            return true;
        }
        return false;
    };
    pGroupTable.domLimWindow = domRightTableWindow;
    pGroupTable.bWithoutHead = false;
    pGroupTable.bStriped = true;
    pGroupTable.bNeedSort = true;
    pGroupTable.bNoneScrollX = true;
    const sGroupName = oGroup.pathEl + "";
    pGroupTable.fDblclick = (oBr) => {
        glob.JobListDblClick(sGroupName, oBr.fGetData().name);
    };
    pGroupTable.fRightBtn = (e, Branch, DTP) => {
        JobContextMenu(jsJobMenu, e.clientX, e.clientY, e.clientX, e.target, false, { Branch, DTP });
    };
    pGroupTable.sPathFieldName = "name";
    for (const it of oGroup.cont) {
        const sJobName = it.fGetData().name;
        let oJobInList = glob.GetJobInList(sJobName);
        if (oJobInList) {
            pGroupTable.root.fAddData(oJobInList, { fDataProcessor: MainJobTableProc });
        }
    }
    domRightTableWindow.innerHTML = "";
    glob.SetRightJobTable(await CreateTable(pGroupTable));
}
function GetJobTreeModeNum(id) {
    const oMode = aJobTreeModes.find(it => it.name == id);
    if (oMode) {
        return oMode.mode;
    }
    return -1;
}
function GetJobTreeModeId(nMode) {
    if (nMode >= 0 && nMode < aJobTreeModes.length) {
        return aJobTreeModes[nMode].name;
    }
    return "";
}
async function SetJobTreeMode(xMode) {
    const nJobMode = (typeof xMode == 'number') ? xMode : GetJobTreeModeNum(xMode);
    const nOldMode = glob.GetTreeMode(sCurrJob);
    if (nJobMode >= 0 && nJobMode <= MAX_TREE_MODE && nJobMode !== nOldMode) {
        try {
            await SendRecivePostApiWithRetry("SwitchJobViewMode", { job_name: sCurrJob, view_mode: nJobMode });
        }
        catch (oErr) {
            CatchErrProcess(oErr, "Set Job Tree Mode", { eGoal: "msgbox" });
            throw "";
        }
        glob.SetTreeMode(sCurrJob, nJobMode);
        RefreshJobTreeRequest(sCurrJob);
    }
}
function MenuJobTreeMode(btn) {
    let rect = btn.getBoundingClientRect();
    CreateDropMenuItems(jsDrpMenuArr, rect.left, rect.bottom, rect.left, btn);
}
const MAX_NUM_BTN_SWITCH_MODE = 6;
;
let jsDrpMenuArr = [];
function CreatePanelOfJobModeView(aModeCntArr, nCurrMode = 2) {
    if (!aModeCntArr || aModeCntArr.length === 0 || !aModeCntArr.find(it => it > 0))
        return;
    const domSwtchTreeFltBtnPnl = document.getElementById("idSwtchTreeFltBtnPnl");
    if (!domSwtchTreeFltBtnPnl) {
        return;
    }
    const domParent = domSwtchTreeFltBtnPnl.parentNode;
    if (domParent) {
        domParent.style.display = "";
    }
    const jsImgMenuArr = [];
    jsDrpMenuArr = [];
    let bCurrModeInGorMenu = false;
    let sCurrModeName = "";
    let nIndCurrModeInModeArr = -1;
    for (let i = 0; i < aJobTreeModes.length; i++) {
        const oMode = aJobTreeModes[i];
        if (oMode.mode > aModeCntArr.length)
            continue;
        const nCnt = aModeCntArr[oMode.mode];
        if (oMode.mode < 2 || nCnt > 0 || nCurrMode == oMode.mode) {
            if (jsImgMenuArr.length < MAX_NUM_BTN_SWITCH_MODE) {
                if (oMode.mode === nCurrMode) {
                    bCurrModeInGorMenu = true;
                    sCurrModeName = oMode.name;
                    nIndCurrModeInModeArr = i;
                    if (nCnt === 0) {
                        if (oMode.hint_if_no) {
                            sHintIfNoTree = oMode.hint_if_no;
                        }
                        else
                            sHintIfNoTree = "Hint_No_Changes";
                    }
                }
                jsImgMenuArr.push({ title: "GetLocaleText('" + oMode.name + "') + ' (" + nCnt + ")'", wo_border: true,
                    img: oMode.img, id: oMode.name, command: "SetJobTreeMode(btn.id)" });
            }
            else {
                if (oMode.mode === nCurrMode) {
                    sCurrModeName = oMode.name;
                    nIndCurrModeInModeArr = i;
                }
                jsDrpMenuArr.push({ title: oMode.name,
                    img: oMode.img, id: oMode.name, command: "SetJobTreeMode(" + oMode.mode + ")", hot_keys_: "(" + nCnt + ")" });
            }
        }
    }
    if (jsDrpMenuArr.length > 0) {
        const img = SetImg("chevron-down", "1rem");
        let chevron = '&#128899;';
        if (img)
            chevron = img.outerHTML;
        if (bCurrModeInGorMenu) {
            jsImgMenuArr.push({
                title: "GetLocaleText('Menu_View') + '   (" + jsDrpMenuArr.length + ") " + chevron + "'",
                img: "views_green", id: "Menu_View", command: "MenuJobTreeMode(btn)", wo_border: true
            });
        }
        else if (nCurrMode >= 0 && nCurrMode < aJobTreeModes.length && nCurrMode < aModeCntArr.length) {
            jsImgMenuArr.push({
                title: "GetLocaleText('" + sCurrModeName + "') + ' (" + aModeCntArr[nCurrMode] + ") " + chevron + "'",
                img: aJobTreeModes[nIndCurrModeInModeArr].img, id: sCurrModeName, command: "MenuJobTreeMode(btn)", wo_border: true
            });
        }
    }
    if (jsImgMenuArr.length > 0) {
        domSwtchTreeFltBtnPnl.style.display = "";
        CreateImgButtonBar(jsImgMenuArr, domSwtchTreeFltBtnPnl, { bHorizontalButtons: true, sSelectId: sCurrModeName });
    }
    DrawDrag();
}
function SetNextDataButton(oTBC) {
    oTBC.oTdProperties = { name: "next_data_dyntabl", __bDisableBG__: true };
    oTBC.bNextDataButton = true;
    return { name: GetLocaleText("Str_AddJobTreeItem", ["" + READ_JOB_TREE_MAX_ITEM]), ldate: "&nbsp;", lsize: "&nbsp;", rdate: "&nbsp;", rsize: "&nbsp;", l: "-", r: "-", c: "-" };
}
async function ConflictResolve(nSpOpNumber) {
    if (!sCurrJob)
        return;
    const sJobName = sCurrJob;
    try {
        await SendRecivePostApiWithRetry("StartSpecOp", { "job_name": sJobName, "spop_type": nSpOpNumber });
    }
    catch { }
    let oJobInList = glob.GetJobInList(sJobName);
    if (oJobInList) {
        oJobInList.bNeedRefreshAfterSpOp = true;
        const domBlockTree = document.getElementById("tree_block");
        if (domBlockTree) {
            domBlockTree.style.display = "";
        }
    }
}
const aJobTreeModes = [
    { name: "Cmd_ShowAll", mode: 0, img: "Show-All" },
    { name: "Cmd_ShowChanges", mode: 1, img: "changes16" },
    { name: "Cmd_ShowConflict", mode: 2, img: "C_Ena_Que_Fil", hint_if_no: "Hint_No_Conflicts" },
    { name: "Str_ToRight", mode: 9, img: "R_Ena_Arr_Fill" },
    { name: "Str_ToLeft", mode: 10, img: "L_Ena_Arr_Fil" },
    { name: "Cmd_ShowError", mode: 3, img: "job_error" },
    { name: "Cmd_ShowIncluded", mode: 4, img: "Filters_plus" },
    { name: "Cmd_ShowExcluded", mode: 5, img: "Filters_minus" },
    { name: "Cmd_ShowToCreate", mode: 6, img: "plus-add-line" },
    { name: "Cmd_ShowToOverwrite", mode: 7, img: "" },
    { name: "Cmd_ShowToDelete", mode: 8, img: "I_Ena_Del" },
    { name: "Cmd_DeleteLeftToRight", mode: 11, img: "R_Del_Arr_Fil" },
    { name: "Cmd_DeleteRightToLeft", mode: 12, img: "L_Del_Arr_Fil" },
    { name: "Cmd_RenameMove_LtoR", mode: 13, img: "" },
    { name: "Cmd_RenameMove_RtoL", mode: 14, img: "" },
    { name: "Cmd_CopyTimeLeftToRight", mode: 15, img: "R_Ena_Ts_Nofl" },
    { name: "Cmd_CopyTimeRightToLeft", mode: 16, img: "L_Ena_Ts_Nofl" },
    { name: "Cmd_NameCaseLeftToRight", mode: 17, img: "R_Ena_Arr_Aa_Nofl" },
    { name: "Cmd_NameCaseRightToLeft", mode: 18, img: "L_Ena_Arr_Aa_Nofl" },
    { name: "Cmd_ShowMergInSync", mode: 19, img: "" },
    { name: "Cmd_ShowSameLenDiffTime", mode: 20, img: "" },
    { name: "Cmd_ShowCountableChanges", mode: 21, img: "" },
    { name: "Cmd_ShowChangesToSync", mode: 22, img: "changes16" },
    { name: "Cmd_ShowNotYetSynced", mode: 23, img: "" },
    { name: "Cmd_ShowAllAll", mode: 24, img: "" },
];
const FLT_ACT_EXC_PATH = 0;
const FLT_ACT_INC_PATH = 1;
const FLT_ACT_EXC_NAME = 2;
const FLT_ACT_INC_NAME = 3;
const FLT_ACT_EXC_MASK = 4;
const FLT_ACT_INC_MASK = 5;
function SetInExclude(sPath, nAct, oFilters) {
    switch (nAct) {
        case FLT_ACT_EXC_PATH:
            {
                oFilters.Excluded.push("path " + sPath);
            }
            break;
        case FLT_ACT_INC_PATH:
            {
                oFilters.Included.push("path " + sPath);
            }
            break;
        case FLT_ACT_EXC_NAME:
            {
                oFilters.Excluded.push("name " + GetOnlyName(sPath));
            }
            break;
        case FLT_ACT_EXC_MASK:
            {
                const sExt = GetOnlyExtention(sPath);
                if (sExt.length > 1)
                    oFilters.Excluded.push("name *" + sExt);
            }
            break;
        case FLT_ACT_INC_MASK:
            {
                const sExt = GetOnlyExtention(sPath);
                if (sExt.length > 1)
                    oFilters.Included.push("name *" + sExt);
            }
            break;
    }
}
function GetTreeItemProps(xArgs) {
    const oData = xArgs.oTreeRow._branch_.fGetData();
    let sMsg = "<table><tr><td style='padding-right:5px;'>Path:</td><td>/" + xArgs.path_arr[0] + "</td></tr>";
    sMsg += "<tr><td style='padding-right:5px;'>OperSys:</td><td>" + GetActStr(oData.sys_act) + "</td></tr>";
    sMsg += "<tr><td style='padding-right:5px;'>OperUsr:</td><td>" + GetActStr(oData.user_act) + "</td></tr>";
    sMsg += "<tr><td style='padding-right:5px;'>Status:</td><td>" + ParseStateTreePair(oData.state) + "</td></tr>";
    sMsg += "<tr><td style='padding-right:5px;'>Lnow:</td><td>" + ParseRLdata(oData.lcur) + "</td></tr>";
    sMsg += "<tr><td style='padding-right:5px;'>Lold:</td><td>" + ParseRLdata(oData.lold) + "</td></tr>";
    sMsg += "<tr><td style='padding-right:5px;'>Rnow:</td><td>" + ParseRLdata(oData.rcur) + "</td></tr>";
    sMsg += "<tr><td style='padding-right:5px;'>Rold:</td><td>" + ParseRLdata(oData.rold) + "</td></tr>";
    HtmlMsgbox(sMsg, xArgs.oTreeRow._branch_.pathEl + " " + GetLocaleText("Cmd_Properties").toLowerCase(), { nWidth: 800 });
}
function GetJobNodeProps(oJobInList) {
    let sMsg = "<table><tr><td style='padding-right:5px;'>Path:</td><td></td></tr>";
    sMsg += "<tr><td style='padding-right:5px;'>OperSys:</td><td>NO_COPY</td></tr>";
    sMsg += "<tr><td style='padding-right:5px;'>OperUsr:</td><td>USESYSTEM</td></tr>";
    sMsg += "<tr><td style='padding-right:5px;'>Status:</td><td>" + (oJobInList.status) + "</td></tr>";
    sMsg += "<tr><td style='padding-right:5px;'>Lnow:</td><td>[folder] accu-time=(not present) attr= cktype=0</td></tr>";
    sMsg += "<tr><td style='padding-right:5px;'>Lold:</td><td>[not-present]</td></tr>";
    sMsg += "<tr><td style='padding-right:5px;'>Rnow:</td><td>[folder] accu-time=(not present) attr= cktype=0</td></tr>";
    sMsg += "<tr><td style='padding-right:5px;'>Rold:</td><td>[not-present]</td></tr>";
    sMsg += "<tr><td style='padding-right:5px;'>Lgen:</td><td>c=0</td></tr>";
    sMsg += "<tr><td style='padding-right:5px;'>Rgen:</td><td>c=0</td></tr>";
    HtmlMsgbox(sMsg, GetLocaleText("Cmd_Properties").toLowerCase(), { nWidth: 800 });
}
function ParseStateTreePair(n) {
    switch (n) {
        case ESS_ANALYZED_OK: return "analyzed OK";
        case ESS_ANALYZED_ERR: return "analyze error";
        case ESS_SYNCING: return "syncing";
        case ESS_SYNCED_OK: return "synced OK";
        case ESS_SYNCED_ERR: return "synced error";
        default: return "undefined";
    }
}
function ParseRLdata(data) {
    if (!data)
        return "";
    let ret = "";
    if (data.is_file) {
        ret += "[file]";
    }
    if (data.is_folder) {
        ret += "[folder]";
    }
    if (data.is_link) {
        ret += "[link]";
    }
    if (!ret) {
        ret += "[not-present]";
    }
    if (data.mod_time) {
        ret += " mod-time=" + GetDTString(data.mod_time) + ";";
    }
    if (data.attrs) {
        ret += " attr=" + data.attrs + ";";
    }
    if (data.cksum) {
        ret += " cksum=" + data.cksum + ", cktype=" + data.cksum_type + ";";
    }
    return ret;
}
function OpenJobMenu(dom) {
    if (!sCurrJob)
        return;
    let rect = dom.getBoundingClientRect();
    JobContextMenu(jsJobMenu, rect.left - 50, rect.bottom + 20, rect.right, dom, false, sCurrJob);
}
function JobContextMenu(jsMenuItems, x, y, x1, el, bAsButton, xAddArgs, fOnClose, sClass) {
    const tmpJobMenu = CopyArray(jsMenuItems);
    const oAddToGroup = tmpJobMenu.find(it => it.title == "Str_AddToGroup");
    if (oAddToGroup && aGlobGroup) {
        if (!xAddArgs) {
            xAddArgs = { DTP: glob.GetActiveJobTable() };
        }
        const aJonNames = [];
        if (typeof xAddArgs === 'string') {
            aJonNames.push(xAddArgs);
        }
        else {
            const nLen = xAddArgs.DTP.fGetSelTabLen();
            if (nLen > 0) {
                for (let i = 0; i < nLen; i++) {
                    aJonNames.push(xAddArgs.DTP.fGetSelBranch(i).fGetData().name);
                }
            }
        }
        if (oAddToGroup && oAddToGroup.submenu) {
            oAddToGroup.submenu.splice(0);
            if (aJonNames.length > 0) {
                for (let it of aGlobGroup) {
                    if (it.m_eGroupType == GROUP_TYPE_USER) {
                        if (it.m_jobsInGroup.find(it => aJonNames.find(it2 => it === it2))) {
                            oAddToGroup.submenu.push({ img: "C_Ena_Chk", "title": it.m_sGroupName, command: "AddJobToGroup('" + it.m_sGroupName + "', xAddArgs)" });
                        }
                        else {
                            oAddToGroup.submenu.push({ "title": it.m_sGroupName, command: "AddJobToGroup('" + it.m_sGroupName + "', xAddArgs)" });
                        }
                    }
                }
            }
            if (oAddToGroup.submenu.length === 0) {
                oAddToGroup.noactive = true;
            }
        }
        CreateDropMenuItems(tmpJobMenu, x, y, x1, el, bAsButton, xAddArgs, fOnClose, sClass);
    }
    else {
        CreateDropMenuItems(jsMenuItems, x, y, x1, el, bAsButton, xAddArgs, fOnClose, sClass);
    }
}
async function JobListWithSmallDataRequest(select, job_names) {
    if (!select || select.length == 0)
        return null;
    try {
        return (await SendRecivePostApiWithRetry("ListJobs", { select, job_names, "max_items": 100 }, { oMultiPageArrs: { jobs: [] } })).jobs;
    }
    catch (oErr) {
        return null;
    }
}
const READ_JOB_TREE_MAX_ITEM = 1000;
const ALL_JOB_TREE_MAX_ITEM = 5000;
async function RefreshJobTreeRequest(sJobName, sPath) {
    if (!sCurrJob || sJobName && sJobName !== sCurrJob)
        return;
    if (!sJobName) {
        sJobName = sCurrJob;
    }
    let oTableRow = undefined;
    const oDTP = jsJobsTables[sJobName];
    if (oDTP) {
        if (!sPath) {
            if (oDTP.root.cont && oDTP.root.cont.length > 0) {
                oDTP.root.cont[0].fClear();
                oDTP.root.cont[0].folder = FOLDER_OPEN;
                oDTP.nFirstShowRow = 0;
                oDTP.nScrollTop = 0;
                if (oDTP.domLimWindow) {
                    oDTP.domLimWindow.scrollTop = 0;
                }
            }
            else {
                delete jsJobsTables[sJobName];
            }
        }
        else {
            oTableRow = oDTP.fFindBranchStr(sPath, "/");
            if (oTableRow) {
                oTableRow.fClear();
            }
        }
    }
    const oParams = { "job_name": sJobName, "path": sPath, "view_mode": glob.GetTreeMode(sJobName), "max_items": READ_JOB_TREE_MAX_ITEM };
    const oDTP1 = await JobTreeReqAndProc(oParams, oTableRow);
    await DisplayJobTree(sJobName, sPath, oDTP1);
}
async function JobTreeRequest(sJobName, oTableRow) {
    if (!sJobName) {
        sJobName = sCurrJob;
    }
    let oJobInList = glob.GetJobInList(sJobName);
    if (!oJobInList || !oJobInList.status)
        return;
    if (oTableRow) {
        let sPath = oTableRow.fGetPathStr("/");
        if (oTableRow.cont && oTableRow.cont.length == 0) {
            const oDTP1 = await JobTreeReqAndProc({ "job_name": sJobName, "path": sPath, "view_mode": glob.GetTreeMode(sJobName), "max_items": READ_JOB_TREE_MAX_ITEM }, oTableRow);
            await DisplayJobTree(sJobName, sPath, oDTP1);
        }
    }
    else {
        let window = document.getElementById("job_tree_window");
        if (window) {
            let oJobTable = jsJobsTables[sJobName];
            if (!oJobTable) {
                const oDTP1 = await JobTreeReqAndProc({ "job_name": sJobName, "path": "", "view_mode": glob.GetTreeMode(sJobName), "max_items": READ_JOB_TREE_MAX_ITEM });
                await DisplayJobTree(sJobName, "", oDTP1);
            }
            else {
                window.innerHTML = "";
                let inWin = document.createElement("div");
                inWin.id = "in_win_job_tree_window";
                window.append(inWin);
                oJobTable.domContainer = inWin;
                oJobTable.domLimWindow = window;
                oJobTable.CreateListElements();
            }
        }
    }
}
async function DisplayJobTree(sJobName, sPath = "", oDTP) {
    const oJobInList = glob.GetJobInList(sJobName);
    if (sPath === "") {
        SetSwitchJobModePanel(oJobInList);
        if (oJobInList) {
            oJobInList.bIsGapInJobTreeChanges = false;
            if (oJobInList.oJobStatus) {
                mapNextTreeChangeIds.set(sJobName, oJobInList.oJobStatus.next_tree_change_id);
            }
        }
    }
    if (oDTP && oDTP.fIsNotEmpty()) {
        await ShowTreeIfThisNeeds(sJobName, oDTP, oJobInList);
    }
    else {
        await ShowTextIfNoTree(oJobInList, (oJobInList && oJobInList.oJobStatus && oJobInList.oJobStatus.job_result != RUN_result_term_error));
    }
}
