////////////////////////////////////////////////////////////////////////////////////////
//Page �꾩뿭 蹂���
////////////////////////////////////////////////////////////////////////////////////////
var dataTableRef;
var windowCount = 0;
var linuxCount = 0;
var unixCount = 0;
var etcCount = 0;
var footerCheck = 0;
var selectedStorData;
var datatableCallback_DuplicateDefence = 0;
var searchString; // 寃��됱뼱
var searchRangeType; //�좎쭨 寃��� 湲곗�. 紐⑤뱺�좎쭨 / 1�� / 7�� / 1�� / 1�� ��...
////////////////////////////////////////////////////////////////////////////////////////
//Document Ready
////////////////////////////////////////////////////////////////////////////////////////
function execDocReady() {
    var pluginGroups = [
        [
            "../reference/light-blue/lib/vendor/jquery.ui.widget.js",
            "../reference/light-blue/lib/vendor/http_blueimp.github.io_JavaScript-Templates_js_tmpl.js",
            "../reference/light-blue/lib/vendor/http_blueimp.github.io_JavaScript-Load-Image_js_load-image.js",
            "../reference/light-blue/lib/vendor/http_blueimp.github.io_JavaScript-Canvas-to-Blob_js_canvas-to-blob.js",
            "../reference/light-blue/lib/jquery.iframe-transport.js",
            "../reference/light-blue/lib/jquery.fileupload.js",
            "../reference/light-blue/lib/jquery.fileupload-fp.js",
            "../reference/light-blue/lib/jquery.fileupload-ui.js"
        ],
        [
            "../reference/jquery-plugins/select2-4.0.2/dist/css/select2_lightblue4.css",
            "../reference/jquery-plugins/lou-multi-select-0.9.12/css/multiselect-lightblue4.css",
            "../reference/jquery-plugins/multiple-select-1.5.2/dist/multiple-select-bluelight.css",
            "../reference/jquery-plugins/select2-4.0.2/dist/js/select2.min.js",
            "../reference/jquery-plugins/lou-multi-select-0.9.12/js/jquery.quicksearch.js",
            "../reference/jquery-plugins/lou-multi-select-0.9.12/js/jquery.multi-select.js",
            "../reference/jquery-plugins/multiple-select-1.5.2/dist/multiple-select.min.js"
        ],
        [
            "../reference/lightblue4/docs/lib/slimScroll/jquery.slimscroll.min.js",
            "../reference/jquery-plugins/unityping-0.1.0/dist/jquery.unityping.min.js",
            "../reference/lightblue4/docs/lib/widgster/widgster.js"
        ],
        [
            // �섏씠�쇱씠��
            "../reference/jquery-plugins/highlight.js-11.10.0/highlight.js.lib/highlight.min.js",
            "../reference/jquery-plugins/highlight.js-11.10.0/highlight.js.lib/src/styles/arta.css",
            // 寃��됱뿏吏�
            "../arms/css/searchEngine.css",
            "../arms/js/searchEngine/searchApiModule.js",
            //�좎쭨 寃���
            "../reference/light-blue/lib/bootstrap-datepicker.js",
            "../reference/jquery-plugins/datetimepicker-2.5.20/build/jquery.datetimepicker.min.css",
            "../reference/jquery-plugins/datetimepicker-2.5.20/build/jquery.datetimepicker.full.min.js"
        ]
        // 異붽��곸씤 �뚮윭洹몄씤 洹몃9�ㅼ쓣 �닿납�� 異붽��섎㈃ �⑸땲��.
    ];

    loadPluginGroupsParallelAndSequential(pluginGroups)
        .then(function () {
            console.log("紐⑤뱺 �뚮윭洹몄씤 濡쒕뱶 �꾨즺");
            //�곷떒 硫붾돱
            $(".widget").widgster();
            setSideMenu("sidebar_menu_system", "sidebar_menu_system_logging");

            setTimeout(function () {
                var script = document.createElement("script");
                script.src = "../reference/jquery-plugins/dataTables-1.10.16/extensions/Buttons/js/vfs_fonts.js";
                script.defer = true; // defer �띿꽦 �ㅼ젙
                document.head.appendChild(script);
            }, 2000); // 2珥� �꾩뿉 �ㅽ뻾�⑸땲��.


            //highlight 湲곕룞
            hljs.highlightAll();
            //寃��� 愿��� �대깽�몃━�ㅻ꼫�쒖꽦��
            eventListenersActivator();
            //�좎쭨寃��� �대깽�몃━�ㅻ꼫
            date_range_filter_event();
            dateTimePicker();
            //寃��됯껐怨�_吏묎퀎
            result_aggs_event();

            //�섏씠吏� 濡쒕뱶 �� - �곷떒 寃��� �뺤씤
            checkQueryStringOnUrl();
        })
        .catch(function (e) {
            console.error("�뚮윭洹몄씤 濡쒕뱶 以� �ㅻ쪟 諛쒖깮");
        });
}

/////////////////////////
//�대깽�� 由ъ뒪�� �쒖꽦�� - 寃��됯껐怨� �좏깮 ��
/////////////////////////
function eventListenersActivator() {
    // 寃��됱갹�� 寃��됱뼱瑜� �j퀬 �뷀꽣瑜� �뚮��� ��.
    $("#search-input").on("keyup", function (event) {
        if (event.keyCode === 13) {
            console.log("[searchEngine.js :: search_start] :: �낅젰媛� => " + $("#search-input").val());
            $("#search-button").click(); //寃��됱떆�� �몃━嫄� ��븷
        }
    });

    $("#search-button").on("click", function (event) {
        $("#nav-search-input").val("");
        let searchTerm = $("#search-input").val();

        寃��됱뼱_�좏슚��_泥댄겕(searchTerm); // �ш린�� �꾩뿭蹂��섏씤 寃��됱뼱 �명똿

        if (searchString) {
            console.log("[searchEngine :: search-button] :: 寃��됱뼱 -> " + searchString);
            setParameter("searchString", searchString);
            let rangeDate = SearchApiModule.getRangeDate();
            search_with_date(checkAndAppendWildcard(searchString), rangeDate);
        } else {
            setParameter("searchString", ""); // 寃��됱뼱 url 珥덇린��
            console.log("[searchEngine :: search-button] :: 寃��됱뼱媛� �녾굅�� 鍮덇컪 �낅땲��.");
        }
    });

    //寃��� 寃곌낵 由ъ뒪�� �대┃ �대깽��
    $(".search_main_wrapper .search_result_group .search_result_items").on("click", function (event) {
        console.log($(event.target).closest(".search-result")[0]);
        var clicked_content_id = $(event.target).closest(".search-result").find(".search_head").attr("id");
        if (!clicked_content_id.includes("no_search_result")) {
            let section_and_order = getDataSectionAndOrder(clicked_content_id);
            SearchApiModule.mapDataToModal(section_and_order["search_section"], section_and_order["order"]);
        }
    });
}

///////////////////////////////////////
// 寃���_�곗씠�� 吏묎퀎 �대깽�몃━�ㅻ꼫
///////////////////////////////////////
function result_aggs_event() {
    // �꾪꽣-�쒕∼�ㅼ슫
    $("#data-result-group").on("click", function (event) {
        console.log("[searchEngine :: 紐⑤뱺 寃곌낵] :: �쒕∼�ㅼ슫 :: 濡쒓렇吏묎퀎 top5 蹂댁뿬二쇨린");

        let rangeDate = SearchApiModule.getRangeDate();
        //寃��됱뼱 泥댄겕 (�녿떎硫�, 寃��됱갹 �뺤씤�섏뿬 �명똿)
        if (searchString) {
            getTop5LogName(searchString, rangeDate);
        } else {
            let no_aggs_data = {
                ko: "吏묎퀎 �곗씠�� �놁쓬",
                en: "No aggregate data",
                jp: "�녻쮫�뉎꺖�욍겒��"
            }[getCookie("locale") || "ko"];

            $("#log-agg-top5").html("");
            var setting = `<a style="text-align: center;">${no_aggs_data}</a>`;
            $("#log-agg-top5").html(setting);
        }
    });
}

//////////////////////////////
// 寃���_�좎쭨�꾪꽣 �대깽�몃━�ㅻ꼫
//////////////////////////////
function date_range_filter_event() {
    $("#date-range-group .dropdown-menu li:not(:last)").on("click", function (event) {
        // console.log($(event.target));
        var rangeTypeId = $(event.target).closest("a").attr("id");
        var rangeText = $("#" + rangeTypeId).text();
        $("#date-range").text(rangeText); // �쒕∼�ㅼ슫 ���댄� 蹂�寃�

        searchRangeType = rangeTypeId; // 寃��� �덉씤吏� ���낆븘�대뵒
        SearchApiModule.setRangeDateAsync(rangeTypeId)
            .then(() => {
                //�좎쭨 援ш컙 �명똿
                let rangeDate = SearchApiModule.getRangeDate();
                let start = rangeDate["start-date"] ? SearchApiModule.setMidnightToZero(rangeDate["start-date"]) : "";
                let end = rangeDate["end-date"]
                    ? new Date(rangeDate["end-date"]).toLocaleString("ko-KR", { timeZone: "Asia/Seoul" })
                    : "";
                let rangeText = start + " ~ " + end;
                let blannk = `&nbsp;&nbsp;`;
                if (searchRangeType === "all-time") {
                    rangeText = "";
                    blannk = ``;
                }
                $("#filter_list").html("");
                $("#filter_list").append(`<li style="margin: 0 3px"><a>${blannk}${rangeText}</a></li>`);

                if (searchString) {
                    //寃��� �ㅽ뻾
                    search_with_date(checkAndAppendWildcard(searchString), rangeDate);
                }
            })
            .catch((error) => {
                console.error("[searchEngine :: �좎쭨寃��� �대깽�몃━�ㅻ꼫] :: 寃��� �ㅻ쪟 諛쒖깮 =>", error);
            });
        console.log(rangeTypeId);
    });

    // 湲곌컙 �ㅼ젙 �좏깮
    $("#date-range-group .dropdown-menu li:last").on("click", function (event) {
        var rangeTypeId = $(event.target).closest("a").attr("id");
        var rangeText = $("#" + rangeTypeId).text();
        $("#date-range").text(rangeText); // �쒕∼�ㅼ슫 ���댄� 蹂�寃�

        $("#date_timepicker_start").val("");
        $("#date_timepicker_end").val("");
    });
}

/////////////////////////
// �섏씠吏� �좎쭨 �ы븿 寃���
/////////////////////////
function search_with_date(search_string, range_date) {
    let start_date = null;
    let end_date = null;
    if (range_date) {
        if (range_date["start-date"]) {
            start_date = range_date["start-date"];
        }
        if (range_date["end-date"]) {
            end_date = range_date["end-date"];
        }
    }

    $(".spinner").html(
        '<img src="./img/loading.gif" alt="濡쒕뵫" style="width: 16px;"> ' +
        {
            ko: "寃��� 寃곌낵 濡쒕뵫 以묒엯�덈떎...",
            en: "Search results are loading...",
            jp: "濾쒐뇨永먩옖�믦き�욤씔�볝겎�꾠겲��..."
        }[getCookie("locale") || "ko"]
    );

    $.ajax({
        url: "/engine-search-api/engine/search/log/with-date",
        type: "GET",
        data: { "search_string": search_string, "page" : 0, "size": 10,"from": start_date, "to" : end_date },
        dataType: "json",
        success: function(result) {
            console.log("[searchEngine :: search_with_date] :: fluentd_search_results  �ㅽ뻾");

            const current_page = 1; //�꾩옱 �섏씠吏� 珥덇린��
            const items_per_Page = 10; //�섏씠吏��� �꾩씠�� ��
            SearchApiModule.setSearchResult("log", result, current_page, items_per_Page);
        }
    });
    getTop5LogName(search_string,range_date);
    // getTop5HostIp(search_string, range_date);
    // getTop5OsType(search_string, range_date);
}

//////////////////////////////////////////////////////////////////
// �섏씠吏� �꾨��� �숈옉 - 寃��� (search_section 蹂� �섏씠吏� 寃���)
//////////////////////////////////////////////////////////////////
function section_search(search_section, page, range_date) {
    var search_string = checkAndAppendWildcard(searchString);
    var pageSize = 10;

    let start_date = null;
    let end_date = null;
    if (range_date) {
        if (range_date["start-date"]) {
            start_date = range_date["start-date"];
        }
        if (range_date["end-date"]) {
            end_date = range_date["end-date"];
        }
    }

    $(".spinner").html(
        '<img src="./img/loading.gif" alt="濡쒕뵫" style="width: 16px;"> ' +
        {
            ko: "寃��� 寃곌낵 濡쒕뵫 以묒엯�덈떎...",
            en: "Search results are loading...",
            jp: "濾쒐뇨永먩옖�믦き�욤씔�볝겎�꾠겲��..."
        }[getCookie("locale") || "ko"]
    );

    $.ajax({
        url: "/engine-search-api/engine/search/" + search_section + "/with-date",
        type: "GET",
        data: { search_string: search_string, page: page, size: pageSize, from: start_date, to: end_date },
        dataType: "json",
        success: function (result) {
            console.log("[searchEngine :: search] :: search_section => " + search_section);
            console.log("[searchEngine :: search] :: search_result => ");
            console.log(result);
            let showPage = page + 1; // 蹂댁뿬二쇰뒗 �섏씠吏�
            SearchApiModule.setSearchResult(search_section, result, showPage, pageSize);
            let pageStart = Math.floor(page / 10) * 10 + 1;
            SearchApiModule.updateButtons(search_section, showPage, pageStart);
        }
    });
}

function getTop5LogName(search_string, range_date) {
    console.log("[searchEngine :: getTop5LogName] �ㅽ뻾");
    $(".spinner").html(
        '<img src="./img/loading.gif" alt="濡쒕뵫" style="width: 16px;"> ' +
        {
            ko: "吏묎퀎 寃곌낵 濡쒕뵫 以묒엯�덈떎...",
            en: "Loading aggregation results...",
            jp: "�녻쮫永먩옖�믦き�욤씔�요릎�㎯걲..."
        }[getCookie("locale") || "ko"]
    );

    let start_date = null;
    let end_date = null;
    if (range_date) {
        if (range_date["start-date"]) {
            start_date = range_date["start-date"];
        }
        if (range_date["end-date"]) {
            end_date = range_date["end-date"];
        }
    }

    $.ajax({
        url: "/engine-search-api/engine/search/log/aggs-top5",
        type: "GET",
        data: { search_string: search_string, from: start_date, to: end_date },
        dataType: "json",
        success: function (result) {
            console.log("[searchEngine :: search_with_date] :: log-aggs-top5 => 吏묎퀎 �ㅽ뻾");
            console.log(result);
            if (result) {
                var resultArr = result["寃��됯껐怨�"]["group_by_@log_name"];
                var appendHtml = ``;

                var total = 0;
                resultArr.forEach((element) => {
                    total += parseInt(element["媛쒖닔"]);
                });
                console.log("[searchEngine :: getTop5LogName] :: log-aggs-top5 :: total => ", total);
                $("#log-agg-top5").html("");
                let no_aggs_data = {
                    ko: "吏묎퀎 �곗씠�� �놁쓬",
                    en: "No aggregate data",
                    jp: "�녻쮫�뉎꺖�욍겒��"
                }[getCookie("locale") || "ko"];
                var setting = `<ul>`;
                if (total === 0) {
                    setting += `<li><a style="text-align: center;">${no_aggs_data}</a></li>`;
                } else {
                    resultArr.forEach((element) => {
                        var ratio = +((parseInt(element["媛쒖닔"]) / total) * 100).toFixed(1);
                        setting += `<li>
							<div style="margin: 5px 10px; display: flex; justify-content: space-between" >
								<p style="color: #a4c6ff; margin-bottom: 0px">${element["�꾨뱶紐�"]}</p>
								<p style="color: #2D8515; margin-bottom: 0px">${element["媛쒖닔"]}(${ratio}%)</p>
							</div>
							<div class="progress progress-small" style="margin: 0 10px 5px 10px">
								<div class="progress-bar progress-bar-inverse" style="width: ${ratio}%;"></div>
							</div>												
						</li>`;
                    });
                    setting += `</ul>`;
                }
                $("#log-agg-top5").html(setting);
            } else {
                $("#log-agg-top5").html(
                    `<a style="text-align: center;">${no_aggs_data}</a>`
                );
            }
        }
    });
}

//////////////////////////////////////////////////
// �대┃�� �꾩씠�붿뿉�� section怨� 寃곌낵�쒖꽌 媛��몄삤湲�
//////////////////////////////////////////////////
function getDataSectionAndOrder(id) {
    const targetId = id;
    // discovery-host | log (�꾩씠�붿뿉�� section order 戮묎린)
    const matches = targetId.match(/hits_order_(discovery|discovery-host|log)_(\d+)/);
    let returnVal = { search_section: null, order: null };

    if (matches) {
        returnVal["search_section"] = matches[1];
        returnVal["order"] = matches[2];
        console.log("[searchEngine :: getDataSectionAndOrder] :: section -> " + matches[1] + ", order -> " + matches[2]);
        return returnVal;
    } else {
        console.log("[searchEngine :: getDataSectionAndOrder] No Match Found :: id -> " + targetId);
        return returnVal;
    }
}

////////////////////////////////////////
// �섏씠吏� 濡쒕뱶 ��, �곷떒 寃��됱뼱 湲곗엯 �뺤씤
////////////////////////////////////////
function checkQueryStringOnUrl() {
    var queryString = window.location.search;
    var urlParams = new URLSearchParams(queryString);
    var searchTerm = urlParams.get("searchString");

    if (searchTerm) {
        $("#search-input").val(searchTerm);
        $("#search-button").click();
    } else {
        console.log("[searchEngine :: checkQueryStringOnUrl] :: �곷떒_寃��� 寃��됱뼱媛� �놁뒿�덈떎.");
    }
}

function changePage(search_section, page) {
    console.log("[searchEngine :: chagne] :: search_section -> " + search_section + ", page -> " + page);
    let requestPage = page - 1;
    if (requestPage < 0) {
        requestPage = 0;
    }
    section_search(search_section, requestPage, SearchApiModule.getRangeDate());
}

////////////////////////////
// 寃��됰궇吏� 湲곌컙 �ㅼ젙 �명똿
////////////////////////////
function dateTimePicker() {
    $("#date_timepicker_start").datetimepicker({
        format: "Y-m-d", // �좎쭨 諛� �쒓컙 �뺤떇 吏���
        formatDate: "Y/m/d",
        timepicker: false,
        theme: "dark",
        lang: "kr",
        onSelectTime: function (current_time, $input) {
            $("#date_timepicker_end").datetimepicker("setOptions", { minDate: current_time });
        },
        onShow: function (ct) {
            this.setOptions({
                maxDate: $("#date_timepicker_end").val() ? $("#date_timepicker_end").val() : false
            });
        }
    });
    $("#date_timepicker_end").datetimepicker({
        format: "Y-m-d", // �좎쭨 諛� �쒓컙 �뺤떇 吏���
        formatDate: "Y/m/d",
        timepicker: false,
        theme: "dark",
        lang: "kr",
        onSelectTime: function (current_time, $input) {
            $("#date_timepicker_start").datetimepicker("setOptions", { maxDate: current_time });
        },
        onShow: function (ct) {
            this.setOptions({
                minDate: $("#date_timepicker_start").val() ? $("#date_timepicker_start").val() : false
            });
        }
    });
}

////////////////////////////
// 寃��됰궇吏� 湲곌컙 �ㅼ젙 紐⑤떖 -
////////////////////////////
function customRangeSetting() {
    console.log("[searchEngine :: customRangeSetting] :: �ㅽ뻾");
    searchRangeType = "custom-range";
    SearchApiModule.setRangeDateAsync("custom-range")
        .then(() => {
            let rangeDate = SearchApiModule.getRangeDate();
            let start = rangeDate["start-date"]
                ? new Date(rangeDate["start-date"]).toLocaleString("ko-KR", { timeZone: "Asia/Seoul" })
                : "";
            let end = rangeDate["end-date"]
                ? new Date(rangeDate["end-date"]).toLocaleString("ko-KR", { timeZone: "Asia/Seoul" })
                : "";
            let rangeText = start + " ~ " + end;
            $("#filter_list").html("");
            $("#filter_list").append(`<li style="margin: 0 3px"><a>${rangeText}</a></li>`);

            if (searchString) {
                console.log("[searchEngine :: customRangeSetting] :: searchString => " + searchString);
                search_with_date(checkAndAppendWildcard(searchString), rangeDate);
            }
        })
        .catch((error) => {
            console.error("[searchEngine :: �좎쭨寃��� �대깽�몃━�ㅻ꼫] :: 寃��� �ㅻ쪟 諛쒖깮 =>", error);
        });
}

function 寃��됱뼱_�좏슚��_泥댄겕(search_string) {
    if (search_string && $.trim(search_string) !== "" && !/^\*+$/.test($.trim(search_string))) {
        let searchTerm = $.trim(search_string);
        searchString = searchTerm;
    } else {
        // url 寃��됱뼱 param 珥덇린��
        setParameter("searchString", "");
        searchString = null;
        console.log("[searchEngine :: 寃��됱뼱_�좏슚��_泥댄겕 ] :: 寃��됱뼱媛� �좏슚�섏� �딆뒿�덈떎.");
    }
}

function checkAndAppendWildcard(searchTerm) {
    // 寃��됱뼱�� 留덉�留� 臾몄옄媛� *�몄� �뺤씤
    if (searchTerm.slice(-1) !== "*") {
        // *�� �녿떎硫� *�� 異붽��섏뿬 諛섑솚
        return searchTerm + "*";
    }
    // *�� �대� �덉쑝硫� 寃��됱뼱瑜� 洹몃�濡� 諛섑솚
    return searchTerm;
}