"use strict";
const nNumberStringInLogStore = 10;
const domLogWindow = document.getElementById("log_window");
const domLogButton = document.getElementById("open_log_window");
const dom_log_close_X = document.getElementById("log_close_X");
const dom_log_menu_button = document.getElementById("log_menu_button");
if (domLogWindow) {
    domLogWindow.onmouseenter = function () {
        isMouseIntoLogWindow = true;
    };
    domLogWindow.onmouseleave = function () {
        isMouseIntoLogWindow = false;
    };
}
if (dom_log_menu_button) {
    dom_log_menu_button.addEventListener('click', function (e) {
        let rect = this.getBoundingClientRect();
        SetLogMenu({ "clientX": rect.left, "clientY": rect.top });
        e.stopPropagation();
    });
}
function IsError(nLevel) {
    return nLevel == 1;
}
function OpenLog() {
    if (domRightBottomWindow.style.display == "none") {
        const nLogWinH = domRightTableWindow.getBoundingClientRect().height;
        if (oSavedData.oJobTableParams.nRightWinH > 50 && (nLogWinH - oSavedData.oJobTableParams.nRightWinH) > MIN_LOG_WIN_HEIGHT) {
            domRightTableWindow.style.flex = "0 0 " + oSavedData.oJobTableParams.nRightWinH + "px";
        }
        else {
            domRightTableWindow.style.flex = "0 0 " + (nLogWinH * 0.7) + "px";
            oSavedData.oJobTableParams.nRightWinH = nLogWinH * 0.7;
            localStorage.setItem("oSavedData", JSON.stringify(oSavedData));
        }
        domRightBottomWindow.style.display = "";
        domRightTableWindow.classList.add("stretch_y");
        if (domRightTableWindow["fUserResize"]) {
            domRightTableWindow.fUserResize();
        }
        SetStretchEl();
        oSavedData.oJobTableParams.bLogWinOpen = true;
        localStorage.setItem("oSavedData", JSON.stringify(oSavedData));
        domRightTableWindow.classList.add("I_have_user_resise");
        domLogButton.style.display = "none";
    }
}
function CloseLog() {
    domRightBottomWindow.style.display = "none";
    domRightTableWindow.style.flex = "1";
    domRightTableWindow.classList.remove("stretch_y");
    oSavedData.oJobTableParams.bLogWinOpen = false;
    localStorage.setItem("oSavedData", JSON.stringify(oSavedData));
    SetStretchEl();
    domRightTableWindow.classList.remove("I_have_user_resise");
    domLogButton.style.display = "";
    if (domRightTableWindow.lastChild && domRightTableWindow.lastChild.fUserResize) {
        domRightTableWindow.lastChild.fUserResize();
    }
}
function ClearLog() {
    domLogWindow.innerHTML = "";
}
function SetLogMenu(e) {
    DeleteAllDropMenu();
    let height = domLogWindow.getBoundingClientRect().height;
    if (!IsLogWindowOpen()) {
        (jsLogMenu.find(item => item.title == "TT_ClearLogs")).noactive = true;
        (jsLogMenu.find(item => item.title == "TT_CloseLogs")).noactive = true;
        (jsLogMenu.find(item => item.title == "TT_OpenLogs")).noactive = false;
    }
    else {
        (jsLogMenu.find(item => item.title == "TT_ClearLogs")).noactive = false;
        (jsLogMenu.find(item => item.title == "TT_CloseLogs")).noactive = false;
        (jsLogMenu.find(item => item.title == "TT_OpenLogs")).noactive = true;
    }
    CreateDropMenuItems(jsLogMenu, e.clientX, e.clientY, e.clientX + 5, null);
}
function IsLogWindowOpen() {
    if (!domRightBottomWindow || domRightBottomWindow.style.display == 'none')
        return false;
    return domRightBottomWindow.getBoundingClientRect().height > MIN_LOG_WIN_HEIGHT;
}
function GetColorOfLogLine(nLevel) {
    switch (nLevel) {
        case 0: return "blue";
        case 1: return "red";
        default: return "#424242";
    }
}
function RewriteLogSettings() {
    ClearLog();
    if (sCurrJob && IsLogWindowOpen()) {
        localStorage.setItem("oSavedData", JSON.stringify(oSavedData));
        oLogIdLastRequest.set(sCurrJob, -1);
    }
}
function ShowMenuOfChoosingLogLevels() {
    let oTmp = CopyObject(oSavedData);
    CreateFloatMenu(jsFloatMenu['ChoosingLogLevels'], { top: "50%", width: "400px" }, oTmp).promise
        .then(data => {
        SetObjFieldsFromAnotherObj(data.data, oSavedData);
        RewriteLogSettings();
    }).catch(() => { });
}
function GetLogStringFromPage() {
    let ret = "";
    let dmArr = document.getElementsByClassName("log_info");
    for (const p of dmArr) {
        let sTmp = p.innerHTML;
        sTmp = sTmp.replaceAll("<b>", "");
        sTmp = sTmp.replaceAll("</b>", "");
        ret += sTmp + "\n";
    }
    return ret;
}
let nForDetectLowerestScroll = 10;
function PutLogStrToWindow(oLogLine) {
    let bIsMaxScroll = (domRightBottomWindow.scrollHeight - domRightBottomWindow.clientHeight - domRightBottomWindow.scrollTop) < nForDetectLowerestScroll;
    let domLogStrP = document.createElement("p");
    domLogStrP.className = "log_info";
    let color = GetColorOfLogLine(oLogLine.level);
    if (color) {
        domLogStrP.style.color = color;
    }
    domLogStrP.innerHTML = "<span>" + GetDTString(oLogLine.time, "woDate") + "</span>" + oLogLine.line;
    domLogWindow.append(domLogStrP);
    if (domLogWindow.children.length > oSavedData.oOpts.nNumLogStrInLogWin) {
        domLogWindow.children[0].remove();
    }
    if (bIsMaxScroll) {
        domRightBottomWindow.scrollTop = domRightBottomWindow.scrollHeight - domRightBottomWindow.clientHeight;
    }
}
function CopyLogToClipBoard() {
    navigator.clipboard.writeText(GetLogStringFromPage()).catch(err => alert("Something went wrong: " + err));
}
async function GetSupportTicketState(domSupportTicketState, oMenu) {
    try {
        if (!oMenu || oMenu.bSelfDeleted) {
            ErrorMsgShow("Canceled by user", { eGoal: "console" });
            const oErr = { message: "Canceled by user", code: -3, data: { error_str: "canceled_by_user", error_num: -3 } };
            throw { src: "user", errData: oErr };
        }
        const oAnswer = await SendRecivePostApiWithRetry("GetSupportTicketState");
        if (oAnswer.state) {
            switch (oAnswer.state) {
                case 0:
                    ErrorMsgShow("Canceled by user", { eGoal: "console" });
                    const oErr1 = { message: "Canceled by user", code: -3, data: { error_str: "canceled_by_user", error_num: -3 } };
                    throw { src: "user", errData: oErr1 };
                case 1:
                    if (!domSupportTicketState.classList.contains("waiting_box")) {
                        domSupportTicketState.classList.add("waiting_box");
                    }
                    await new Promise(ttt => setTimeout(ttt, 1000));
                    return await GetSupportTicketState(domSupportTicketState, oMenu);
                case 2:
                    if (domSupportTicketState.classList.contains("waiting_box")) {
                        domSupportTicketState.classList.remove("waiting_box");
                    }
                    if (oAnswer.progress_message) {
                        domSupportTicketState.innerHTML = oAnswer.progress_message;
                    }
                    await new Promise(ttt => setTimeout(ttt, 1000));
                    return await GetSupportTicketState(domSupportTicketState, oMenu);
                case 3:
                    if (oAnswer.result_url) {
                        return oAnswer.result_url;
                    }
                    ErrorMsgShow("Failed to create support ticket", { eGoal: "both" });
                    const oErr3 = { message: "Failed to create support ticket", code: -5, data: { error_str: "failed_ticket", error_num: -5 } };
                    throw { src: "user", errData: oErr3 };
                case 4:
                    if (oAnswer.error) {
                        ErrorMsgShow(oAnswer.error, { eGoal: "both" });
                    }
                    const oErr2 = { message: oAnswer.error, code: -4, data: { error_str: "GetSupportTicketStateError", error_num: -4 } };
                    throw { src: "user", errData: oErr2 };
            }
        }
    }
    catch (err) {
        throw err;
    }
}
async function CreateSupportTicket() {
    let oMenu = null;
    try {
        const oAnswer = await SendRecivePostApiWithRetry("CreateSupportTicket");
        const jsWaitingSupportTicketBox = {
            title: "Creating Support Ticket", bottom_box: [], cont: [
                { title: "", cont: [
                        { type: "place", title: "", id: "support_ticket_state" },
                        { type: "link", value: "", id: "support_ticket_link" },
                    ] }
            ]
        };
        const oWaitingBox = CreateFloatMenu(jsWaitingSupportTicketBox, { top: "20%", width: "40%" }, null);
        oMenu = oWaitingBox.oMenu;
        oWaitingBox.promise.then(() => { }).catch(() => { });
        const domSupportTicketState = document.getElementById("support_ticket_state_" + oWaitingBox.oMenu.id);
        if (!domSupportTicketState) {
            ErrorMsgShow("Failed to create support ticket", { eGoal: "both" });
            const oErr = { message: "Failed to create support ticket", code: -6, data: { error_str: "support_ticket_state_place_fail", error_num: -6 } };
            throw { src: "dom", errData: oErr };
        }
        const sUrl = await GetSupportTicketState(domSupportTicketState, oMenu);
        if (!sUrl) {
            ErrorMsgShow("Failed to create support ticket", { eGoal: "both" });
            const oErr = { message: "Failed to create support ticket", code: -7, data: { error_str: "support_ticket_state_place_fail", error_num: -7 } };
            throw { src: "dom", errData: oErr };
        }
        const domSupportTicketLink = document.getElementById("support_ticket_link_" + oWaitingBox.oMenu.id);
        if (domSupportTicketLink) {
            domSupportTicketState.innerHTML = GetLocaleText("Str_ClickSupportTicketLink");
            domSupportTicketLink.href = sUrl;
            domSupportTicketLink.click();
            domSupportTicketLink.parentElement.style.textAlign = "center";
            domSupportTicketLink.innerHTML = "Support Ticket Link";
        }
        else {
            ErrorMsgShow("Failed to create support ticket", { eGoal: "both" });
            const oErr = { message: "Failed to create support ticket link", code: -8, data: { error_str: "support_ticket_link_fail", error_num: -8 } };
            throw { src: "dom", errData: oErr };
        }
    }
    catch (err) {
        if (oMenu) {
            oMenu.fCloseMenu();
        }
    }
}
async function OpenLogInSide(sSide) {
    const oJobInList = glob.GetJobInList(sCurrJob);
    if (!oJobInList) {
        HtmlErrBox("Job Name is wrong", "Error of log folder opening");
        return;
    }
    let sUrl = (sSide == 'left') ? oJobInList.left_url : oJobInList.right_url;
    if (!sUrl) {
        HtmlErrBox("Job " + sSide + " side is not selected", "Error of log folder opening");
        return;
    }
    const urlWithPath = new URL(location.origin + location.pathname + '/static/LogView.html');
    urlWithPath.searchParams.set('url', sUrl);
    urlWithPath.searchParams.set('side', sSide);
    const nInd = (sSide == 'left') ? 0 : 1;
    urlWithPath.searchParams.set('key', oJobInList.oSideCoords[nInd].sAcctKeyA);
    if (oJobInList.oSideCoords[nInd].opts && oJobInList.oSideCoords[nInd].opts.bNoGsData) {
        const url = ParseUrl(oJobInList.oSideCoords[nInd].conn.sUrlA);
        const sUserId = oJobInList.oSideCoords[nInd].conn.sUserIdA;
        let sPath = (url.protocol + "-"
            + (sUserId ? sUserId + "@" : "")
            + url.hostname + "-"
            + (url.port ? url.port + "-" : "")
            + url.pathname).replaceAll(":", "-").replaceAll("\/", "-");
        while (sPath.includes("--")) {
            sPath = sPath.replaceAll("--", "-");
        }
        if (sPath) {
            urlWithPath.searchParams.set('path', sPath);
        }
    }
    window.open(urlWithPath, '_blank');
}
async function GSLogViewer(sUrl, sAccKey, sSide, sPath) {
    let oUrl = ParseUrl(sUrl);
    let oWaitinBoxMenu = null;
    try {
        const jsWaitingFileListBox = {
            title: GetLocaleText("Str_LogFilesSearching"), bottom_box: [], cont: [
                { title: "", cont: [
                        { type: "text", title: "<b>Path: " + sUrl + "</b></br>" },
                        { type: "place", title: "- Start of Log files searching -", id: "LogFilesSearching_state", class: "nowrap_nooverflow_ellipse" },
                    ] }
            ]
        };
        const oWaitingBox = CreateFloatMenu(jsWaitingFileListBox, { top: "20%", width: "40%" }, null);
        oWaitingBox.promise.then(() => { }).catch(() => { });
        const domPlace = document.getElementById("LogFilesSearching_state_" + oWaitingBox.oMenu.id);
        domPlace.innerText = "Getting Account data of " + sAccKey;
        oWaitinBoxMenu = oWaitingBox.oMenu;
        let oAccArrs = null;
        let sGsDataFolder = "\/_gsdata_";
        if (sPath) {
            domPlace.innerText = "Getting JobServer Mirror Folder";
            const oJobServerAboutInfoResult = await SendRecivePostApiWithRetry("GetAboutInfo", {}, { domMenu: oWaitingBox.oMenu });
            if (oJobServerAboutInfoResult.effective_mirror_folder) {
                oUrl = ParseUrl(oJobServerAboutInfoResult.effective_mirror_folder);
                oUrl.pathname += "\/" + sPath;
                sGsDataFolder = "";
                sUrl = oUrl.pathname;
                oAccArrs = await SendRecivePostApiWithRetry("ListAccounts", { "fs_url": oUrl.protocol, max_items: 1 }, { oMultiPageArrs: { accounts: [], hints: [] }, domMenu: oWaitingBox.oMenu });
            }
        }
        if (!oUrl.pathname.startsWith("\/")) {
            oUrl.pathname = "\/" + oUrl.pathname;
        }
        if (!oAccArrs) {
            oAccArrs = await SendRecivePostApiWithRetry("ListAccounts", { "fs_url": oUrl.protocol, start_from: sAccKey, max_items: 1 }, { oMultiPageArrs: { accounts: [], hints: [] }, domMenu: oWaitingBox.oMenu });
            if (!oAccArrs || oAccArrs.accounts.length < 1 && (!oWaitingBox.oMenu || !oWaitingBox.oMenu.bSelfDeleted)) {
                CloseFloatMenu(oWaitinBoxMenu);
                HtmlErrBox("Job " + sSide + " side account " + GetLocaleText("Err_NotFound"), "Error of log folder opening");
                return;
            }
        }
        const oParams = { folder_coords: { conn: oAccArrs.accounts[0].AcctConn, sAcctKeyA: oAccArrs.accounts[0].Key } };
        const sServerAndPath = ((IsFsGST(oAccArrs.accounts[0].AcctConn.sUrlA)) ?
            GetServerName(oAccArrs.accounts[0].AcctConn.sUrlA, sUrl, oAccArrs.accounts[0].AcctConn.sUserIdA) : "") + oUrl.pathname;
        let oBookmarks = (oAccArrs.accounts[0].UnnamedBookmarks && oAccArrs.accounts[0].UnnamedBookmarks.length) ?
            oAccArrs.accounts[0].UnnamedBookmarks.find(bm => (bm.Opts.nCompressType > 1 || bm.Opts.bEncryptBodies || bm.Opts.bEncryptPaths) && bm.BmkKey == sServerAndPath) : null;
        if (oBookmarks) {
            oParams.folder_coords.opts = oBookmarks.Opts;
            oParams.folder_coords.sServerDirA = oBookmarks.BmkKey;
            oParams.folder_coords.sBmkNameA = oBookmarks.BmkKey;
        }
        let oFsConnectData = null;
        const sServerPath = oUrl.protocol + oUrl.hostname;
        if (oAccArrs.hints.length > 0 && oAccArrs.hints[0].hint_properties.list_servers) {
            const oServerList = await SendRecivePostApiWithRetry("ListServers", { "conn": oAccArrs.accounts[0].AcctConn }, { domMenu: oWaitingBox.oMenu });
            domPlace.innerText = "Servers listing of " + oUrl.protocol + sAccKey;
            if (oServerList && oServerList.servers) {
                const oServer = oServerList.servers.find(it => it.sUrlA == sServerPath);
                if (!oServer && (!oWaitingBox.oMenu || !oWaitingBox.oMenu.bSelfDeleted)) {
                    CloseFloatMenu(oWaitinBoxMenu);
                    HtmlErrBox(sServerPath + " " + GetLocaleText("Err_NotFound"), "Error of log folder opening");
                    return;
                }
                oServerList.out_conn.sUrlA = sServerPath + oUrl.port + oUrl.pathname;
                domPlace.innerText = "Connecting to " + sServerPath;
                oParams.folder_coords.conn = oServerList.out_conn;
                oFsConnectData = await SendRecivePostApiWithRetry("ConnectFS", oParams);
            }
            else {
                if (!oWaitingBox.oMenu || !oWaitingBox.oMenu.bSelfDeleted) {
                    CloseFloatMenu(oWaitinBoxMenu);
                    HtmlErrBox(sServerPath + " " + GetLocaleText("Err_NotFound"), "Error of log folder opening");
                }
                return;
            }
        }
        else {
            domPlace.innerText = "Connecting to " + sServerPath;
            oAccArrs.accounts[0].AcctConn.sUrlA = sServerPath + oUrl.port + oUrl.pathname;
            oFsConnectData = await SendRecivePostApiWithRetry("ConnectFS", oParams);
        }
        domPlace.innerText = "";
        domPlace.innerHTML = "Listing log files from " + sServerPath + "<span style='margin:0 5px'></span>" + GetWaitingSvg(2);
        const aFolderList = await SendRecivePostApiWithRetry("ListDir", {
            "filesys_handle": oFsConnectData.filesys_handle,
            "path": sGsDataFolder,
            "max_items": LIST_DIR_MAX_ITEM
        }, { oMultiPageArrs: { items: [] }, domMenu: oWaitingBox.oMenu });
        if (!aFolderList && (!oWaitingBox.oMenu || !oWaitingBox.oMenu.bSelfDeleted)) {
            CloseFloatMenu(oWaitingBox.oMenu);
            HtmlErrBox(GetLocaleText("Err_LogFiles") + oUrl.pathname + sGsDataFolder + " " + GetLocaleText("Err_NotFound"), "Error of log folder opening");
            return;
        }
        const aLogfFileList = aFolderList.items.filter(item => { return item.bIsFile && GetFileExtension(item.sNameA).toLowerCase() == ".log"; });
        CloseFloatMenu(oWaitingBox.oMenu);
        const oDTP = new CDynTabProp;
        oDTP.bOnlyOneSelRow = true;
        oDTP.aHead = [{ field_name: "sNameA", col_name: "Log file names" },];
        oDTP.root.fAddDataArr(aLogfFileList);
        const obj = { oDTP: oDTP, sSearchText: "", bCaseSens: false };
        const jsLogDisplayBox = {
            title: "Log files on " + GetPathForShow(sUrl), bottom_box: [], cont: [
                { title: "", cont: [
                        { type: "row", id: "control_elements", cont: [
                                { type: "button", title: "Copy All", img: "copy", class: "img_btn_gor_wo_border", command: "CopyFromLogViewer(oMenu)", w_s: "nowrap" },
                                { type: "button", title: "Copy selected", img: "copy", class: "img_btn_gor_wo_border", command: "CopyFromLogViewer(oMenu, true)", w_s: "nowrap" },
                                { type: "space", w: "1rem" },
                                { type: "textfield", value: "sSearchText", id: "SearchText", el_class: "text_for_searching fltmn_textfield" },
                                { type: "button", img: "find", class: "img_btn_gor_wo_border thin_btn", command: "FindTextInLogViewer(oMenu)" },
                                { type: "button", img: "chevron-down", class: "img_btn_gor_wo_border thin_btn", command: "FindNexTextInLogViewer(oMenu, 'down')" },
                                { type: "button", img: "chevron-up", class: "img_btn_gor_wo_border thin_btn", command: "FindNexTextInLogViewer(oMenu, 'up')" },
                                { type: "checkbox", title: "Search_Case_Sensitive", value: "bCaseSens" },
                                { type: "place", id: "nFromN" },
                            ] },
                        { type: "row", h: "100%", class: "flex_gor_top", cont: [
                                { type: "table", title: "", dynTable: "oDTP", w: 210, class: "browse_dialog_table stretch_x", minH: "calc(100% - 5px)", maxH: "calc(100% - 5px)" },
                                { type: "text", title: "", id: "log_text", class: "log_show_window" },
                            ] },
                    ] }
            ]
        };
        const oLogWindow = CreateFloatMenu(jsLogDisplayBox, { width: "100%", height: -100 }, obj, { bNoTitle: true, bNoborder: true, bNoModal: true, bNoResize: true });
        oLogWindow.promise.catch(() => { });
        oLogWindow.oMenu.fFind = () => FindTextInLogViewer(oLogWindow.oMenu);
        domForSearching = document.getElementById("log_wait_text_" + oLogWindow.oMenu.id);
        oLogWindow.oMenu.fCloseMenu = (bIsEsc) => {
            domForSearching = null;
            CloseFloatMenu(oLogWindow.oMenu, bIsEsc);
        };
        const domNfromM = document.getElementById("nFromN_" + oLogWindow.oMenu.id);
        if (domNfromM) {
            domNfromM.style.width = "100px";
            domNfromM.style.textAlign = "right";
            domNfromM.style.whiteSpace = "nowrap";
        }
        const domControlElements = document.getElementById("control_elements_" + oLogWindow.oMenu.id);
        if (domControlElements) {
            SetResetDisabledOfAllChildren(domControlElements, true);
        }
        const domLogText = document.getElementById("log_wait_text_" + oLogWindow.oMenu.id);
        if (domLogText) {
            domLogText.oncontextmenu = (e) => {
                e.preventDefault();
                const x = e.clientX;
            };
        }
        oDTP.fRowClick = async function (branch) {
            if (domNfromM) {
                domNfromM.innerHTML = "";
            }
            domForSearching.innerHTML = GetWaitingSvg(3);
            const sFileName = branch.fGetData().sNameA;
            const sKey = sUrl + "\/" + sFileName;
            let sFileContent = "";
            try {
                try {
                    sFileContent = await GetLogEntry(sKey);
                }
                catch (e) {
                    sFileContent = await AsyncDownloadFile(oFsConnectData.filesys_handle, sGsDataFolder + "\/" + sFileName);
                    try {
                        PutLogEntry(sKey, sFileContent);
                    }
                    catch (e1) { }
                }
                if (sFileContent) {
                    domForSearching.innerText = sFileContent;
                }
                if (domControlElements) {
                    SetResetDisabledOfAllChildren(domControlElements, false);
                }
            }
            catch (catchData) {
                if (catchData.error.data && catchData.error.data.error_str == "disconnected") {
                    oFsConnectData = await SendRecivePostApiWithRetry("ConnectFS", oParams);
                    sFileContent = await AsyncDownloadFile(oFsConnectData.filesys_handle, sGsDataFolder + "\/" + sFileName);
                    try {
                        PutLogEntry(sKey, sFileContent);
                    }
                    catch (e1) { }
                    if (sFileContent) {
                        domForSearching.innerText = sFileContent;
                    }
                }
                else {
                    if (catchData && catchData.error && catchData.error.message) {
                        HtmlErrBox(catchData.error.message, "Error of log folder opening");
                    }
                    else {
                        HtmlErrBox(JSON.stringify(catchData), "Error of log folder opening");
                    }
                }
                CloseFloatMenu(oWaitinBoxMenu);
            }
        };
        if (oDTP.root.cont && oDTP.root.cont.length > 0) {
            oDTP.root.cont[0].fMarkSelf(oDTP);
            oDTP.ShowRows();
            TableRowClick(oDTP, oDTP.root.cont[0]);
        }
    }
    catch (catchData) {
        if (!oWaitinBoxMenu || oWaitinBoxMenu.bSelfDeleted)
            return;
        CloseFloatMenu(oWaitinBoxMenu);
        if (catchData && catchData.error && catchData.error.message) {
            if ("extData" in catchData) {
                if (catchData.error.data.error_str == "not_found") {
                    const oExtData = JSON.parse(catchData.extData);
                    if (oExtData && oExtData.metod == "ListDir") {
                        ErrorMsgShow("There is no log folder " + sUrl);
                        return;
                    }
                }
            }
            ErrorMsgShow(catchData.error.message);
        }
    }
}
function CopyFromLogViewer(oMenu, bCopySel) {
    const domLogText = document.getElementById("log_wait_text_" + oMenu.id);
    if (!domLogText)
        return;
    let sTextForClipboard = bCopySel ? GetSelectTextInElement(domLogText) : domLogText.innerText;
    if (sTextForClipboard) {
        navigator.clipboard.writeText(sTextForClipboard)
            .then(() => { }).catch(err => {
            alert('Something went wrong: ' + err);
        });
    }
}
function FindTextInLogViewer(oMenu) {
    const domLogText = document.getElementById("log_wait_text_" + oMenu.id);
    const domSearchText = document.getElementById("SearchText_" + oMenu.id);
    if (!domLogText || !domSearchText)
        return;
    let sSearchText = domSearchText.value;
    const sSel = GetSelectTextInElement(domLogText);
    if (sSel) {
        sSearchText = sSel;
        domSearchText.value = sSel;
    }
    if (!sSearchText)
        return;
    const aSpans = domLogText.getElementsByTagName("span");
    for (const oSpan of aSpans) {
        oSpan.style.background = "";
    }
    const sLogText = domLogText.innerHTML.replaceAll("<span>", "").replaceAll("</span>", "").replaceAll('<span style="">', "");
    domLogText.innerHTML = oMenu.jsFloatMenuDescr.bCaseSens ? sLogText.replaceAll(sSearchText, "<span>" + sSearchText + "</span>") : AddSpan(sLogText, sSearchText);
    if (oMenu.jsFloatMenuDescr) {
        oMenu.jsFloatMenuDescr.nSelect = -1;
    }
    const domNfromM = document.getElementById("nFromN_" + oMenu.id);
    if (domNfromM) {
        const aSpans2 = domLogText.getElementsByTagName("span");
        domNfromM.innerText = "(" + aSpans2.length + ")";
    }
}
function FindNexTextInLogViewer(oMenu, eDirect) {
    const domLogText = document.getElementById("log_wait_text_" + oMenu.id);
    if (!domLogText)
        return;
    const aSpans = domLogText.getElementsByTagName("span");
    if (aSpans.length < 1)
        return;
    for (const oSpan of aSpans) {
        oSpan.style.background = "";
    }
    if (oMenu.jsFloatMenuDescr) {
        if (oMenu.jsFloatMenuDescr.nSelect === undefined) {
            oMenu.jsFloatMenuDescr.nSelect = 0;
        }
        else {
            oMenu.jsFloatMenuDescr.nSelect += (eDirect == "up") ? -1 : 1;
        }
        if (oMenu.jsFloatMenuDescr.nSelect >= aSpans.length) {
            oMenu.jsFloatMenuDescr.nSelect = 0;
        }
        else if (oMenu.jsFloatMenuDescr.nSelect < 0) {
            oMenu.jsFloatMenuDescr.nSelect = aSpans.length - 1;
        }
        aSpans[oMenu.jsFloatMenuDescr.nSelect].style.background = "#00ff00";
        const rectLogWin = domLogText.getBoundingClientRect();
        const rectSel = aSpans[oMenu.jsFloatMenuDescr.nSelect].getBoundingClientRect();
        if (rectSel.bottom > rectLogWin.bottom) {
            domLogText.scrollTop += rectSel.bottom - rectLogWin.bottom + 5;
        }
        else if (rectSel.top < rectLogWin.top) {
            domLogText.scrollTop -= rectLogWin.top - rectSel.top + 5;
        }
        const domNfromM = document.getElementById("nFromN_" + oMenu.id);
        if (domNfromM) {
            domNfromM.innerText = "(" + (oMenu.jsFloatMenuDescr.nSelect + 1) + "/" + aSpans.length + ")";
        }
    }
}
function DeleteIndexedDBDatabase(dbName) {
    console.log(`Attempt to delete database: ${dbName}`);
    const deleteRequest = window.indexedDB.deleteDatabase(dbName);
    deleteRequest.onsuccess = () => {
        console.log(`Database "${dbName}" successfully deleted.`);
    };
    deleteRequest.onerror = () => {
        console.log(`Error deleting database "${dbName}":`);
    };
    deleteRequest.onblocked = () => {
        console.warn(`Deleting database "${dbName}" is blocked. It may be open in another tab. Close all connections to this database.`);
    };
}
const DB_NAME = "logDB";
const STORE_NAME = "logs";
const DB_VERSION = 1;
DeleteIndexedDBDatabase(DB_NAME);
async function PutLogEntry(key, data) {
    try {
        const _DB_NAME = DB_NAME;
        const _STORE_NAME = STORE_NAME;
        const openRequest = indexedDB.open(_DB_NAME, DB_VERSION);
        openRequest.onupgradeneeded = (event) => {
            const db = event.target.result;
            if (!db.objectStoreNames.contains(_STORE_NAME)) {
                db.createObjectStore(_STORE_NAME);
            }
        };
        openRequest.onerror = (event) => {
            const error = event.target.error;
            console.log(`Error opening database "${_DB_NAME}":`, error);
            throw null;
        };
        openRequest.onsuccess = (event) => {
            const db = event.target.result;
            try {
                const transaction = db.transaction([_STORE_NAME], "readwrite");
                transaction.oncomplete = () => {
                    return;
                };
                transaction.onerror = (event) => {
                    const error = event.target.error;
                    console.log(`Transaction error writing key "${key}":`, error);
                    throw (error);
                };
                transaction.onabort = (event) => {
                    const error = event.target.error;
                    console.log(`Transaction writing key "${key}" was aborted:`, error);
                    throw (new Error(`Transaction  was aborted: ${error?.message || 'Unknown cause'}`));
                };
                transaction.objectStore(_STORE_NAME).put(data, key);
            }
            catch (e) {
                console.log("Unable to start transaction:", e);
                db.close();
                throw (new Error("Unable to start transaction. The connection to the database may be expired or closed."));
            }
        };
        openRequest.onblocked = () => {
            console.log(`Request to open DB ${_DB_NAME} blocked. There may be another tab open with this site using an older version of the DB. Close it.`);
            throw (new Error(`Opening of database ${_DB_NAME} is blocked. Please close other tabs with this site.`));
        };
    }
    catch { }
}
async function GetLogEntry(key) {
    return new Promise((resolve, reject) => {
        const _DB_NAME = DB_NAME;
        const _STORE_NAME = STORE_NAME;
        const openRequest = indexedDB.open(_DB_NAME, DB_VERSION);
        openRequest.onerror = (event) => reject(event.target.error);
        openRequest.onupgradeneeded = (event) => {
            const db = event.target.result;
            if (!db.objectStoreNames.contains(_STORE_NAME)) {
                db.createObjectStore(_STORE_NAME);
            }
            db.close();
            reject(new Error('DB is empty'));
        };
        openRequest.onsuccess = (event) => {
            const db = event.target.result;
            if (!db.objectStoreNames.contains(_STORE_NAME)) {
                console.log(`Storage "${_STORE_NAME}" not found in DB "${_DB_NAME}".`);
                db.close();
                reject();
                return;
            }
            const transaction = db.transaction([_STORE_NAME], "readonly");
            transaction.onerror = (event) => reject(event.target.error);
            transaction.onabort = (event) => reject(new Error('Transaction aborted'));
            const getRequest = transaction.objectStore(_STORE_NAME).get(key);
            getRequest.onsuccess = () => {
                if (typeof getRequest.result !== 'string') {
                    reject(new Error('There is not tis log'));
                }
                else {
                    resolve(getRequest.result);
                }
            };
            getRequest.onerror = (event) => reject(event.target.error);
        };
        openRequest.onblocked = (event) => reject(new Error('DB open request blocked'));
    });
}
