"use strict";
function CreateImgButtonBar(jsButtonList, container, params) {
    if (!params)
        params = {};
    if (!jsButtonList || jsButtonList.length === 0 || !container) {
        return;
    }
    if (!params.bDontClearContainer) {
        container.innerHTML = "";
    }
    AddImgButtonBar(jsButtonList, container, params);
}
function AddImgButtonBar(jsButtonList, container, params) {
    if (!params)
        params = {};
    let j = 0;
    for (let iButton of jsButtonList) {
        if (iButton.checkbox) {
            const el = document.createElement("input");
            el.type = 'checkbox';
            el.className = "fltmn_checkbox";
            el.checked = eval(iButton.checkbox);
            el.addEventListener('change', function () {
                eval(iButton.checkbox + "= el.checked");
            });
            let sTitle = iButton.title;
            if (sTitle.includes("GetLocaleText")) {
                sTitle = eval(iButton.title);
            }
            else {
                sTitle = GetLocaleText(iButton.title);
            }
            const label = document.createElement("label");
            label.className = "chb_btn_gor_sel";
            label.append(el);
            label.append(sTitle);
            container.append(label);
            continue;
        }
        let btn = document.createElement('button');
        if (params.sClass)
            btn.classList.add(params.sClass);
        let sTitle = iButton.title;
        if (sTitle.includes("GetLocaleText")) {
            sTitle = eval(iButton.title);
        }
        else {
            sTitle = GetLocaleText(iButton.title);
        }
        if (params.bHorizontalButtons) {
            if (params.sSelectId && iButton.id && iButton.id == params.sSelectId) {
                btn.className = "img_btn_gor_sel       nonselect";
            }
            else if (iButton.dark) {
                btn.className = "img_btn_gor_dark      nonselect";
            }
            else if (iButton.wo_border) {
                btn.className = "img_btn_gor_wo_border nonselect";
            }
            else {
                btn.className = "img_btn_gor           nonselect";
            }
            let img;
            if (iButton.img) {
                let sImgH = "var(--horizontal-img-btn-size)";
                if (params.sImgSizeH) {
                    sImgH = params.sImgSizeH;
                }
                let sImgW = "";
                if (params.sImgSizeW) {
                    sImgW = params.sImgSizeW;
                }
                img = SetImg(iButton.img, sImgH, "", sImgW);
                if (img) {
                    btn.append(img);
                }
            }
            if (sTitle) {
                if (img) {
                    img.style.marginRight = "0.3rem";
                }
                btn.innerHTML += sTitle;
            }
        }
        else {
            btn.className = "img_btn_bar nonselect";
            if (iButton.img) {
                let sImgH = "var(--horizontal-img-btn-size)";
                if (params.sImgSizeH) {
                    sImgH = params.sImgSizeH;
                }
                let sImgW = "";
                if (params.sImgSizeW) {
                    sImgW = params.sImgSizeW;
                }
                const img = SetImg(iButton.img, sImgH, "", sImgW);
                if (img) {
                    btn.append(img);
                }
            }
            if (sTitle)
                btn.innerHTML += "<br>" + GetLocaleText(iButton.title);
        }
        if (iButton.data) {
            const sData = "<span class='img_btn_data' id='" + ((iButton.id) ? iButton.id + "_data" : (j++) + "_data") + "'> (0) </span>";
            let pos = -1;
            if (iButton.data.before) {
                pos = btn.innerHTML.indexOf(iButton.data.before);
            }
            else if (iButton.data.after) {
                pos = btn.innerHTML.indexOf(iButton.data.after);
                if (pos >= 0) {
                    pos += iButton.data.after.length;
                }
            }
            else if (iButton.data.instad) {
                pos = btn.innerHTML.indexOf(iButton.data.instad);
                btn.innerHTML = btn.innerHTML.replace(iButton.data.instad, "");
            }
            if (pos < 0) {
                btn.innerHTML += sData;
            }
            else {
                btn.innerHTML = btn.innerHTML.substring(0, pos) + sData + btn.innerHTML.substring(pos);
            }
        }
        if (iButton.command) {
            btn.addEventListener('click', function (e) {
                if (!(this.style.opacity == "0.5")) {
                    e.stopPropagation();
                    DeleteAllDropMenu();
                    const title = iButton.title;
                    eval(iButton.command);
                }
            });
        }
        if (iButton.id) {
            btn.id = iButton.id;
        }
        if (iButton.group) {
            btn.className += " " + iButton.group;
        }
        container.append(btn);
    }
}
async function GetCommonAutoRun() {
    try {
        const oAns = await SendRecivePostApiWithRetry("GetSuspendGlobalAutoRun");
        if (oAns.suspend_autorun) {
            EnableClassEl("common_auto_off");
            DisableClassEl("common_auto_on");
        }
        else {
            EnableClassEl("common_auto_on");
            DisableClassEl("common_auto_off");
        }
        return oAns.suspend_autorun;
    }
    catch (oErr) {
        throw oErr;
    }
}
async function SetCommonAutoRun(bOn) {
    try {
        const oAns = await SendRecivePostApiWithRetry("SetSuspendGlobalAutoRun", { suspend_autorun: bOn });
        if (oAns.suspend_autorun) {
            EnableClassEl("common_auto_off");
            DisableClassEl("common_auto_on");
        }
        else {
            EnableClassEl("common_auto_on");
            DisableClassEl("common_auto_off");
        }
    }
    catch (oErr) {
        throw oErr;
    }
}
function CreateNewJob() {
    const obj = { sNewJobName: "", eJobDirection: 0 };
    const jsCreateJobDialog = { title: "Btn_CreateNewJob",
        "bottom_box": [
            { title: "Btn_Ok", "default": true, command: "AsyncCreateNewJob+" },
            { title: "Btn_Cancel", close: true }
        ], cont: [
            { title: "", cont: [
                    { type: "row", "h": "5px", cont: [] },
                    { type: "textfield", title: "Str_JobName", value: "sNewJobName", optional: true },
                    { type: "row", "h": "5px", cont: [] },
                    { type: "radio", value: "eJobDirection", listImg: [
                            { text: "Str_JobType_TwoWay", img: "arrow-left-right" },
                            { text: "Str_JobType_LeftToRight", img: "move-right" },
                            { text: "Str_JobType_RightToLeft", img: "move-left" }
                        ] },
                    { type: "row", "h": "5px", cont: [] },
                ] }
        ]
    };
    CreateFloatMenu(jsCreateJobDialog, { top: '30%', width: '450px' }, obj, { fontSize: "16px", lineHeight: "2" }).promise.catch(() => { });
}
async function AsyncCreateNewJob(oMenu) {
    try {
        await SendRecivePostApiWithRetry("CreateJob", { "job_name": oMenu.jsFloatMenuDescr.sNewJobName, "eJobDirection": oMenu.jsFloatMenuDescr.eJobDirection });
        sNewJob = oMenu.jsFloatMenuDescr.sNewJobName;
    }
    catch (oErr) {
        CatchErrProcess(oErr);
    }
    CloseFloatMenu(oMenu);
}
async function CloneJob(xAddArgs) {
    if (!xAddArgs && !sCurrJob)
        return;
    if (!xAddArgs) {
        xAddArgs = sCurrJob;
    }
    else if (!(typeof xAddArgs === 'string')) {
        if (xAddArgs.Branch) {
            xAddArgs = xAddArgs.Branch.fGetData().name;
        }
        else if (xAddArgs.DTP && xAddArgs.DTP.fGetSelTabLen() === 1) {
            xAddArgs = xAddArgs.DTP.fGetSelBranch(0).fGetData().name;
        }
    }
    const obj = { sNewJobName: xAddArgs + " (clone)" };
    const oRenameMenu = CreateFloatMenu(jsFloatMenu.RenameOrCloneJobDialog, { top: '30%', width: '450px' }, obj, { fontSize: "16px", lineHeight: "2" });
    oRenameMenu.oMenu.domTitle.innerHTML = GetLocaleText("Title_CloneJob") + " <b>" + xAddArgs + "</b>";
    try {
        try {
            await oRenameMenu.promise;
        }
        catch {
            throw null;
        }
        const sCloneJobName = obj.sNewJobName.trim();
        if (!obj.sNewJobName || xAddArgs == sCloneJobName)
            return;
        const oJobData = await SendRecivePostApiWithRetry("GetJobByName", { "job_name": xAddArgs });
        await SendRecivePostApiWithRetry("CreateJob", { "job_name": sCloneJobName, "eJobDirection": 0 });
        oJobData.opt.sName = sCloneJobName;
        oJobData.opt.atOnFileChange = 0;
        oJobData.opt.atOnFolderConnect = 0;
        oJobData.opt.atOnStart = 0;
        oJobData.opt.atOnTimer = 0;
        oJobData.opt.atOnLogout = 0;
        oJobData.opt.atOnSchedule = 0;
        await SendRecivePostApiWithRetry("SetJobOptions", { "job_name": sCloneJobName, "options": oJobData.opt });
        sNewJob = sCloneJobName;
    }
    catch (oErr) {
        CatchErrProcess(oErr);
    }
    CloseFloatMenu(oRenameMenu.oMenu);
}
async function SwapJobSides(xAddArgs) {
    if (!xAddArgs && !sCurrJob)
        return;
    if (!xAddArgs) {
        xAddArgs = sCurrJob;
    }
    else if (!(typeof xAddArgs === 'string')) {
        if (xAddArgs.Branch) {
            xAddArgs = xAddArgs.Branch.fGetData().name;
        }
        else if (xAddArgs.DTP && xAddArgs.DTP.fGetSelTabLen() === 1) {
            xAddArgs = xAddArgs.DTP.fGetSelBranch(0).fGetData().name;
        }
    }
    try {
        const oJob = await SendRecivePostApiWithRetry("GetJobByName", { "job_name": xAddArgs });
        const tmpCoords = oJob.opt.side_coords[0];
        oJob.opt.side_coords[0] = oJob.opt.side_coords[1];
        oJob.opt.side_coords[1] = tmpCoords;
        const tmpOpts = oJob.opt.side_opts[0];
        oJob.opt.side_opts[0] = oJob.opt.side_opts[1];
        oJob.opt.side_opts[1] = tmpOpts;
        if (oJob.opt.eJobDirection === JS_LEFT_TO_RIGHT) {
            oJob.opt.eJobDirection = JS_RIGHT_TO_LEFT;
        }
        else if (oJob.opt.eJobDirection === JS_RIGHT_TO_LEFT) {
            oJob.opt.eJobDirection = JS_LEFT_TO_RIGHT;
        }
        const oNew = await SendRecivePostApiWithRetry("SetJobOptions", { "job_name": xAddArgs, "options": oJob.opt });
        glob.SettingJobInListFields(oNew.new_options, xAddArgs);
        FillCurrJobDetalesWindow(true);
    }
    catch (oErr) {
        CatchErrProcess(oErr);
    }
}
function CreateNewGroup() {
    const obj = { sNewGroupName: "" };
    const jsCreateGroupDialog = { title: "Btn_CreateNewGroup",
        "bottom_box": [
            { title: "Btn_Ok", "default": true, command: "AsyncCreateNewGroup+" },
            { title: "Btn_Cancel", close: true }
        ], cont: [
            { title: "", cont: [
                    { type: "row", "h": "5px", cont: [] },
                    { type: "textfield", title: "Str_GroupName", value: "sNewGroupName" },
                ] }
        ]
    };
    CreateFloatMenu(jsCreateGroupDialog, { top: '30%', width: '450px' }, obj, { fontSize: "16px", lineHeight: "2" }).promise.catch(() => { });
}
async function AsyncCreateNewGroup(oMenu) {
    try {
        await SendRecivePostApiWithRetry("CreateGroup", { "group_name": oMenu.jsFloatMenuDescr.sNewGroupName });
        CloseFloatMenu(oMenu);
        await ListGroupRequest(oMenu.jsFloatMenuDescr.sNewGroupName);
    }
    catch (oErr) {
        CatchErrProcess(oErr);
    }
}
async function RenameJob(xAddArgs) {
    if (!xAddArgs) {
        xAddArgs = sCurrJob;
    }
    else if (!(typeof xAddArgs === 'string')) {
        if (xAddArgs.Branch) {
            xAddArgs = xAddArgs.Branch.fGetData().name;
        }
        else if (xAddArgs.DTP && xAddArgs.DTP.fGetSelTabLen() === 1) {
            xAddArgs = xAddArgs.DTP.fGetSelBranch(0).fGetData().name;
        }
    }
    const obj = { sNewJobName: xAddArgs };
    const oRenameMenu = CreateFloatMenu(jsFloatMenu.RenameOrCloneJobDialog, { top: '30%', width: '450px' }, obj, { fontSize: "16px", lineHeight: "2" });
    oRenameMenu.oMenu.domTitle.innerHTML = GetLocaleText("Title_RenameJob") + " <b>" + xAddArgs + "</b>";
    try {
        await oRenameMenu.promise;
        if (xAddArgs != obj.sNewJobName.trim()) {
            await RenameJobRequest(xAddArgs, obj.sNewJobName.trim());
        }
    }
    catch { }
    CloseFloatMenu(oRenameMenu.oMenu);
}
async function GetAndShowJobOptions(xArg) {
    let sMenuItemForAutoOpening = "";
    let sJobName = sCurrJob;
    const jsOptions = CopyObject(jsFloatMenu.JobOptions);
    if (typeof xArg === 'string') {
        sMenuItemForAutoOpening = xArg;
    }
    else if (xArg && xArg.Branch) {
        sJobName = xArg.Branch.fGetData().name;
        if (!sCurrJob) {
            jsOptions.title = sJobName + " " + GetLocaleText("Str_Options");
        }
    }
    if (sJobName == "")
        return;
    try {
        const oJobData = await SendRecivePostApiWithRetry("GetJobByName", { "job_name": sJobName });
        jsCurrJobOptions = oJobData.opt;
        if (!sCurrJob || sCurrJob == oJobData.opt.sName) {
            SetJobOptionMenu(jsOptions, sMenuItemForAutoOpening);
        }
        else {
            await AsyncHtmlConfirm(GetLocaleText("Qsn_DoYouWantReturnJob", [oJobData.opt.sName, sCurrJob]), "Getting Job Options", eMyConfDefBtn.ok);
            ChangeCurrJob(oJobData.opt.sName, "");
            FillRightWindow();
            SetJobOptionMenu(jsOptions, sMenuItemForAutoOpening);
        }
    }
    catch (oErr) {
        CatchErrProcess(oErr, "GetJobByName '" + (oErr ? oErr.src : "") + ":");
    }
}
async function DeleteJob(xAddArgs) {
    if (!xAddArgs) {
        xAddArgs = { DTP: glob.GetActiveJobTable() };
    }
    if (!(typeof xAddArgs === 'string') && xAddArgs.DTP) {
        const n = xAddArgs.DTP.fGetSelTabLen();
        const aJobNames = [];
        for (let i = 0; i < n; i++) {
            aJobNames.push(xAddArgs.DTP.fGetSelBranch(i).fGetData().name);
        }
        try {
            await AsyncHtmlConfirm(GetLocaleText("Qst_JobsDelete", [aJobNames.length + "", aJobNames.join("<br>")]), "Title_JobsDelete", eMyConfDefBtn.cancel, { bNoCurrJobName: true });
            const aErrs = [];
            for (const sName of aJobNames) {
                try {
                    await DeleteJobRequest(sName);
                }
                catch (oErr) {
                    if (oErr) {
                        if (oErr.error && oErr.error.message) {
                            aErrs.push(oErr.error.message);
                        }
                        else if (oErr.message) {
                            aErrs.push(oErr.message);
                        }
                    }
                }
            }
            if (aErrs.length > 0) {
                HtmlErrBox(aErrs.join("<br>"), "Title_JobsDelete");
            }
        }
        catch { }
        return;
    }
    let sJobName = "";
    if (typeof xAddArgs === 'string') {
        sJobName = xAddArgs;
    }
    else if (xAddArgs.Branch) {
        sJobName = xAddArgs.Branch.fGetData().name;
    }
    else {
        return;
    }
    try {
        await AsyncHtmlConfirm("<p>" + GetLocaleText("Qst_JobDelete") + " <b>'" + sJobName + "'</b> ?", "Title_JobsDelete", eMyConfDefBtn.none, { bNoCurrJobName: true });
        await DeleteJobRequest(sJobName);
    }
    catch (oErr) {
        CatchErrProcess(oErr);
    }
}
function IsGroupSelected() {
    let oDTP = glob.GetActiveJobTable(true);
    if (!oDTP)
        return false;
    if (oDTP && oDTP.fGetSelTabLen() > 0 && oDTP.bIsTree && oDTP.fGetSelRow(0)._level_ === 0)
        return true;
    return false;
}
function IsJobActive(xJobName) {
    return IsJobInListActive(glob.GetJobInList(xJobName));
}
function IsJobInListActive(oJobInList) {
    return oJobInList && oJobInList.oJobStatus &&
        (oJobInList.oJobStatus.job_run_state == "analyze_running" ||
            oJobInList.oJobStatus.job_run_state == "sync_running" ||
            oJobInList.oJobStatus.job_run_state == "spop_running");
}
function IsJobCanBeCleaned(xJobName) {
    let oJobInList = glob.GetJobInList(xJobName);
    return oJobInList && oJobInList.oJobStatus &&
        (oJobInList.oJobStatus.job_run_state == "analyze_done" ||
            oJobInList.oJobStatus.job_run_state == "sync_done" ||
            oJobInList.oJobStatus.job_run_state == "spop_done" ||
            oJobInList.oJobStatus.job_run_state == "Error");
}
function IsJobReadyToAnalize(xJobName) {
    let oJobInList = glob.GetJobInList(xJobName);
    return oJobInList && oJobInList.oJobStatus && !!oJobInList.left_url && !!oJobInList.right_url && (!domErr || !domErr.innerHTML)
        && oJobInList.oJobStatus.job_run_state != "analyze_running"
        && oJobInList.oJobStatus.job_run_state != "sync_running"
        && oJobInList.oJobStatus.job_run_state != "spop_running";
}
function IsJobStateWoTree(job_run_state) {
    return job_run_state == "Error"
        || job_run_state == "not_analyzed"
        || job_run_state == "not_connected";
}
function IsJobReadyToSync(xJobName) {
    let oJobInList = glob.GetJobInList(xJobName);
    return oJobInList && oJobInList.oJobStatus && oJobInList.oJobStatus.job_run_state == "analyze_done";
}
function IsJobHaveAuto(xJob) {
    let oTreeItemData;
    if (typeof xJob == 'string' || "Branch" in xJob) {
        const tmp = glob.GetJobInList(xJob);
        if (!tmp)
            return false;
        oTreeItemData = tmp;
    }
    else {
        oTreeItemData = xJob;
    }
    if (oTreeItemData && oTreeItemData.bHaveAutoOpt)
        return true;
    return false;
}
function PauseJob(xJobName) {
    alert("Not implemented yet");
    return;
    if (!xJobName) {
        xJobName = sCurrJob;
    }
    else if (!(typeof xJobName === 'string')) {
    }
}
function StopJob(xJobName) {
    if (!xJobName) {
        if (!sCurrJob) {
            StopJobFromDropMenuGroup();
        }
        else {
            StopOneJob(sCurrJob);
        }
    }
    else if (typeof xJobName === 'string') {
        StopOneJob(xJobName);
    }
    else if (xJobName.DTP) {
        const nSelTabLen = xJobName.DTP.fGetSelTabLen();
        if (nSelTabLen > 0) {
            for (let i = 0; i < nSelTabLen; i++) {
                StopOneJob(xJobName.DTP.fGetSelBranch(i).fGetData().name);
            }
        }
        else {
            StopOneJob(xJobName.Branch.fGetData().name);
        }
    }
}
function StopOneJob(sJobName) {
    let oJobInList = glob.GetJobInList(sJobName);
    if (oJobInList) {
        if (!IsJobInListActive(oJobInList)) {
            oJobInList.stop_go = false;
            oJobInList.stop_forsed = false;
            return;
        }
        else if (oJobInList.stop_go == true) {
            StopRequest(sJobName, true);
        }
        else {
            StopRequest(sJobName);
        }
    }
    else {
        StopRequest(sJobName);
    }
}
async function ClearJob(xJobName) {
    if (!xJobName) {
        xJobName = sCurrJob;
    }
    else if (!(typeof xJobName === 'string')) {
        xJobName = xJobName.Branch.fGetData().name;
    }
    try {
        await SendRecivePostApiWithRetry("ResetJob", { "job_name": xJobName });
        delete jsJobsTables[xJobName];
        setNeedResetJob.delete(xJobName);
    }
    catch { }
}
function OnlyOneSelectedJob(xJobName) {
    const oDTP = glob.GetActiveJobTable();
    return oDTP && oDTP.fGetSelTabLen() === 1 && oDTP.fGetSelBranch(0).folder === undefined;
}
function FindExtraJobs(aJobStatuses) {
    const aExtraJobInd = [];
    for (let i = 0; i < glob.GetJobArr().length; i++) {
        if (!aJobStatuses.find(it => it.sJobName == glob.GetJobArr()[i].name) && sDeletedJob != glob.GetJobArr()[i].name) {
            aExtraJobInd.push(glob.GetJobArr()[i].name);
        }
    }
    if (aExtraJobInd.length > 0) {
        DeleteJobFromTables(aExtraJobInd);
    }
}
async function SmtpOAuth(sProvider, oMenu) {
    if (!oMenu || oMenu.bSelfDeleted)
        return false;
    try {
        const oAuthResult = await SendRecivePostApiWithRetry("StartOAuth", { conn: { sUrlA: sProvider } });
        if (!openPopup(oAuthResult.consent_url, "windowName: string", 600, 600))
            return false;
        while (oMenu && !oMenu.bSelfDeleted) {
            const ans = await SendRecivePostApiWithRetry("GetOAuthState", { session_handle: oAuthResult.session_handle });
            if (!oMenu || oMenu.bSelfDeleted)
                return false;
            switch (ans.state) {
                case 2:
                    const oPOG = oMenu.jsFloatMenuDescr.CProgramOptionsGlobal;
                    oPOG.m_SmtpServer.m_sOAuthUserIdA = ans.result_conn.sUserIdA;
                    oPOG.m_SmtpServer.m_sOAuthEmail = ans.result_conn.sUserEmailA;
                    oPOG.m_SmtpServer.m_sRefreshTokenEncMasterA = await EncryptStringWithKey(ans.result_conn.sRefreshTokenA, oSavedData.key, oSavedData.iv);
                    await SendRecivePostApiWithRetry("SetGlobalProgramOptions", { "options": oPOG });
                    const domEmail = document.getElementById("e_mail_" + oMenu.id);
                    if (domEmail) {
                        domEmail.value = ans.result_conn.sUserEmailA;
                    }
                    const domUserId = document.getElementById("user_id_" + oMenu.id);
                    if (domUserId) {
                        domUserId.value = ans.result_conn.sUserIdA;
                    }
                    const btnSignOut = document.getElementById("btnSignOut_" + oMenu.id);
                    if (btnSignOut) {
                        btnSignOut.disabled = false;
                    }
                    const btnSignMicrosoft = document.getElementById("btnSignMicrosoft_" + oMenu.id);
                    if (btnSignMicrosoft) {
                        btnSignMicrosoft.disabled = true;
                    }
                    const btnSignGoogle = document.getElementById("btnSignGoogle_" + oMenu.id);
                    if (btnSignGoogle) {
                        btnSignGoogle.disabled = true;
                    }
                    return true;
                case 3:
                    const oErr = { message: ans.error, code: -4, data: { error_str: "authorization_error", error_num: -4 } };
                    throw { src: "", errData: oErr };
            }
            await new Promise(tmp => setTimeout(tmp, 1000));
        }
    }
    catch (oErr) {
        CatchErrProcess(oErr);
    }
}
