"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
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, false, 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, false, 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);
    }
}
function GetCommonAutoRun() {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const oAns = yield AsyncUnicSendRecivePostApiWithRetry("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;
        }
    });
}
function SetCommonAutoRun(bOn) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const oAns = yield AsyncUnicSendRecivePostApiWithRetry("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", nofinal: true, "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(() => { });
}
function AsyncCreateNewJob(oMenu) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            yield AsyncUnicSendRecivePostApiWithRetry("CreateJob", { "job_name": oMenu.jsFloatMenuDescr.sNewJobName, "eJobDirection": oMenu.jsFloatMenuDescr.eJobDirection });
            sNewJob = oMenu.jsFloatMenuDescr.sNewJobName;
            CloseFloatMenu(oMenu);
        }
        catch (catchErr) {
            if (catchErr.error && catchErr.error.message) {
                ErrorMsgShow("CreateJobErr", catchErr.error.message, "msgbox");
            }
        }
    });
}
function CreateNewGroup() {
    const obj = { sNewGroupName: "" };
    const jsCreateGroupDialog = { title: "Btn_CreateNewGroup",
        "bottom_box": [
            { title: "Btn_Ok", nofinal: true, "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(() => { });
}
function AsyncCreateNewGroup(oMenu) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            yield AsyncUnicSendRecivePostApiWithRetry("CreateGroup", { "group_name": oMenu.jsFloatMenuDescr.sNewGroupName });
            CloseFloatMenu(oMenu);
            yield ListGroupRequest(oMenu.jsFloatMenuDescr.sNewGroupName);
        }
        catch (catchErr) {
            if (catchErr.error && catchErr.error.message) {
                ErrorMsgShow("CreateJobErr", catchErr.error.message, "msgbox");
            }
            else {
                ErrorMsgShow("CreateJobErr", JSON.stringify(catchErr), "msgbox");
            }
        }
    });
}
function RenameJob(xAddArgs) {
    if (!xAddArgs) {
        xAddArgs = sCurrJob;
    }
    else if (!(typeof xAddArgs === 'string')) {
        xAddArgs = xAddArgs.Branch.fGetData().name;
    }
    const obj = { sNewJobName: xAddArgs };
    CreateFloatMenu(jsFloatMenu["RenameJobDialog"], { top: '30%', width: '450px' }, obj, { fontSize: "16px", lineHeight: "2" }).promise
        .then(oDialogResalt => {
        if (oDialogResalt.command == "create" && xAddArgs != obj.sNewJobName) {
            RenameJobRequest(xAddArgs, obj.sNewJobName);
        }
    }).catch(() => { });
}
function DeleteJob(xAddArgs) {
    if (!xAddArgs) {
        xAddArgs = sCurrJob;
    }
    else if (!(typeof xAddArgs === 'string')) {
        xAddArgs = xAddArgs.Branch.fGetData().name;
    }
    HtmlConfirm("<p>" + GetLocaleText("Qst_JobDelete") + " <b>'" + xAddArgs + "'</b> ?", "", eMyConfDefBtn.none, { sFontSize: "1.25rem" })
        .then(() => {
        DeleteJobRequest(xAddArgs);
    }).catch(() => { });
}
function GetJobInList(xJobName) {
    if (!xJobName) {
        xJobName = sCurrJob;
    }
    else if (!(typeof xJobName === 'string')) {
        xJobName = xJobName.Branch.fGetData().name;
    }
    return aGlobJobArray.find(item => item.name == xJobName);
}
function IsJobActive(xJobName) {
    return IsJobInListActive(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 IsJobReadyToAnalize(xJobName) {
    let oJobInList = 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 IsJobReadyToSync(xJobName) {
    let oJobInList = GetJobInList(xJobName);
    return oJobInList && oJobInList.oJobStatus && oJobInList.oJobStatus.job_run_state == "analyze_done";
}
function IsJobHaveAuto(xJob) {
    if (typeof xJob == 'string' || xJob.Branch) {
        xJob = GetJobInList(xJob);
    }
    if (xJob.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) {
        xJobName = sCurrJob;
    }
    else if (!(typeof xJobName === 'string')) {
        xJobName = xJobName.Branch.fGetData().name;
    }
    let oJobInList = GetJobInList(xJobName);
    if (oJobInList) {
        if (!IsJobInListActive(oJobInList)) {
            oJobInList.stop_go = false;
            oJobInList.stop_forsed = false;
            return;
        }
        else if (oJobInList.stop_go == true) {
            StopRequest(xJobName, true);
        }
        else {
            StopRequest(xJobName);
        }
    }
    else {
        StopRequest(xJobName);
    }
}
function OnlyOneSelectedJob(xJobName) {
    return xJobName && xJobName.DTP && xJobName.DTP.fGetSelTabLen() === 1 &&
        xJobName.DTP.aDeploedTable[xJobName.DTP.fGetSelRowNum(0)]._branch_.folder === undefined;
}
function FindExtraJobs(aJobStatuses) {
    const aExtraJobInd = [];
    for (let i = 0; i < aGlobJobArray.length; i++) {
        if (!aJobStatuses.find(it => it.sJobName == aGlobJobArray[i].name) && sDeletedJob != aGlobJobArray[i].name) {
            aExtraJobInd.push(aGlobJobArray[i].name);
        }
    }
    if (aExtraJobInd.length > 0) {
        DeleteJobFromTables(aExtraJobInd);
    }
}
function SmtpOAuth(sProvider, oMenu) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!oMenu || oMenu.bSelfDeleted)
            return false;
        try {
            const oAuthResult = yield AsyncUnicSendRecivePostApiWithRetry("StartOAuth", { conn: { sUrlA: sProvider } });
            if (!openPopup(oAuthResult.consent_url, "windowName: string", 600, 600))
                return false;
            while (oMenu && !oMenu.bSelfDeleted) {
                const ans = yield AsyncUnicSendRecivePostApiWithRetry("GetOAuthState", { session_handle: oAuthResult.session_handle });
                if (!oMenu || oMenu.bSelfDeleted)
                    return false;
                switch (ans.state) {
                    case 2:
                        oMenu.jsFloatMenuDescr.CProgramOptionsGlobal.m_SmtpServer.m_sOAuthUserIdA = ans.result_conn.sUserIdA;
                        const domUserId = document.getElementById("user_id_" + oMenu.id);
                        if (domUserId) {
                            domUserId.value = ans.result_conn.sUserIdA;
                        }
                        oMenu.jsFloatMenuDescr.CProgramOptionsGlobal.m_SmtpServer.m_sOAuthEmail = ans.result_conn.sUserEmailA;
                        const domEmail = document.getElementById("e_mail_" + oMenu.id);
                        if (domEmail) {
                            domEmail.value = ans.result_conn.sUserEmailA;
                        }
                        oMenu.jsFloatMenuDescr.CProgramOptionsGlobal.m_SmtpServer.m_sRefreshTokenEncMasterA =
                            yield EncryptStringWithKey(ans.result_conn.sRefreshTokenA, oWebGuSettings.key, oWebGuSettings.iv);
                        return true;
                    case 3:
                        const oErr = { message: ans.error, code: -4, data: { error_str: "authorization_error", error_num: -4 } };
                        throw { src: "", errData: oErr };
                }
                yield new Promise(tmp => setTimeout(tmp, 1000));
            }
        }
        catch (oErr) {
            if (oErr && oErr.src && oErr.error.message) {
                ErrorMsgShow("OAuth " + sProvider, oErr.error.message, "msgbox");
            }
        }
    });
}
