////////////////////////////////////////////////////////////////////////////////////////
//Page �꾩뿭 蹂���
////////////////////////////////////////////////////////////////////////////////////////
var selectId; // �쒗뭹 �꾩씠��
var selectName; // �쒗뭹 �대쫫
var selectedIndex; // �곗씠�고뀒�대툝 �좏깮�� �몃뜳��
var selectedPage; // �곗씠�고뀒�대툝 �좏깮�� �몃뜳��
var selectVersion; // �좏깮�� 踰꾩쟾 �꾩씠��
var dataTableRef; // �곗씠�고뀒�대툝 李몄“ 蹂���

////////////////////////////////////////////////////////////////////////////////////////
//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/unityping-0.1.0/dist/jquery.unityping.min.js",
            "../reference/jquery-plugins/cron-editor-master/css/jquery-ui_arms.css",
            "../reference/jquery-plugins/cron-editor-master/js/jquery-ui.js",
            "../reference/jquery-plugins/cron-editor-master/js/jquery.croneditor_arms.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",
            //highlight
            "../reference/jquery-plugins/highlight.js-11.10.0/highlight.js.lib/src/styles/base16/darcula.css",
            "../reference/jquery-plugins/highlight.js-11.10.0/highlight.js.lib/highlight.min.js",
            "../reference/jquery-plugins/highlight.js-11.10.0/highlightjs-line-numbers.js/src/highlightjs-line-numbers.js"
        ],

        [
            "../reference/jquery-plugins/datetimepicker-2.5.20/build/jquery.datetimepicker.min.css",
            "../reference/light-blue/lib/bootstrap-datepicker.js",
            "../reference/jquery-plugins/datetimepicker-2.5.20/build/jquery.datetimepicker.full.min.js",
            "../reference/lightblue4/docs/lib/widgster/widgster.js",
            "../reference/lightblue4/docs/lib/slimScroll/jquery.slimscroll.min.js",
            "../reference/jquery-plugins/jspreadsheet-ce-4.13.1/dist/jsuites.js",
            "../reference/jquery-plugins/jspreadsheet-ce-4.13.1/dist/index.js",
            "../reference/jquery-plugins/jspreadsheet-ce-4.13.1/dist/jsuites.css",
            "../reference/jquery-plugins/jspreadsheet-ce-4.13.1/dist/jspreadsheet.css",
            "../reference/jquery-plugins/jspreadsheet-ce-4.13.1/dist/jspreadsheet.datatables.css",
            "../reference/jquery-plugins/jspreadsheet-ce-4.13.1/dist/jspreadsheet.theme.css",
            "/arms/js/common/jspreadsheet/spreadsheet.js"
        ],

        [
            "../reference/jquery-plugins/dataTables-1.10.16/media/css/jquery.dataTables_lightblue4.css",
            "../reference/jquery-plugins/dataTables-1.10.16/extensions/Responsive/css/responsive.dataTables_lightblue4.css",
            "../reference/jquery-plugins/dataTables-1.10.16/extensions/Select/css/select.dataTables_lightblue4.css",
            "../reference/jquery-plugins/dataTables-1.10.16/media/js/jquery.dataTables.min.js",
            "../reference/jquery-plugins/dataTables-1.10.16/extensions/Responsive/js/dataTables.responsive.min.js",
            "../reference/jquery-plugins/dataTables-1.10.16/extensions/Select/js/dataTables.select.min.js",
            "../reference/jquery-plugins/dataTables-1.10.16/extensions/RowGroup/js/dataTables.rowsGroup.min.js",
            "../reference/jquery-plugins/dataTables-1.10.16/extensions/Buttons/js/dataTables.buttons.min.js",
            "../reference/jquery-plugins/dataTables-1.10.16/extensions/Buttons/js/buttons.html5.js",
            "../reference/jquery-plugins/dataTables-1.10.16/extensions/Buttons/js/buttons.print.js",
            "../reference/jquery-plugins/dataTables-1.10.16/extensions/Buttons/js/jszip.min.js"
        ]
        // 異붽��곸씤 �뚮윭洹몄씤 洹몃9�ㅼ쓣 �닿납�� 異붽��섎㈃ �⑸땲��.
    ];

    loadPluginGroupsParallelAndSequential(pluginGroups)
        .then(function () {
            console.log('紐⑤뱺 �뚮윭洹몄씤 濡쒕뱶 �꾨즺');

            //vfs_fonts �뚯씪�� 而ㅼ꽌 defer 泥섎━ ��.
            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);
            }, 5000); // 5珥� �꾩뿉 �ㅽ뻾�⑸땲��.

            //pdfmake �뚯씪�� 而ㅼ꽌 defer 泥섎━ ��.
            setTimeout(function () {
                var script = document.createElement("script");
                script.src = "../reference/jquery-plugins/dataTables-1.10.16/extensions/Buttons/js/pdfmake.min.js";
                script.defer = true; // defer �띿꽦 �ㅼ젙
                document.head.appendChild(script);
            }, 5000); // 5珥� �꾩뿉 �ㅽ뻾�⑸땲��.

            // �ъ씠�� 硫붾돱 �됱긽 �ㅼ젙
            $(".widget").widgster();
            setSideMenu("sidebar_menu_config", "sidebar_menu_config_schedule");

            // �곗씠�� �뚯씠釉� 濡쒕뱶 �⑥닔
            var waitDataTable = setInterval(function () {
                try {
                    if (!$.fn.DataTable.isDataTable("#schedule_list_table")) {
                        dataTableLoad();
                        clearInterval(waitDataTable);
                    }
                } catch (err) {
                    console.log("�쒕퉬�� �곗씠�� �뚯씠釉� 濡쒕뱶媛� �꾨즺�섏� �딆븘�� 珥덇린�� �ъ떆�� 以�...");
                }
            }, 313 /*milli*/);

            // Excel
            drawExcel("schedule_history_excel");

            // �щ줎�먮뵒��
            cronInit();

            // �섏씠�쇱씠��
            hljs.highlightAll();
            hljs.initLineNumbersOnLoad({
                // singleLine:true,
                // startFrom: 5,
            });

            //  Element
            var inputarea = document.getElementById("input");
            var outputarea = document.getElementById("output");

            inputarea.addEventListener("input", function (event) {
                outputarea.innerHTML = inputarea.value;
                inputarea.style.zIndex = 4;
                //
                refreshHighlighting();
            }, false);

            function refreshHighlighting() {
                hljs.highlightAll();
                hljs.initLineNumbersOnLoad({
                    // singleLine:true,
                    // startFrom: 5,
                });
            }

        })
        .catch(function (error) {
            console.error("�뚮윭洹몄씤 濡쒕뱶 以� �ㅻ쪟 諛쒖깮");
            console.log(error);
        });
}


////////////////////////////////////////////////////////////////////////////////////////
// --- �щ줎 而⑦듃濡� --- //
////////////////////////////////////////////////////////////////////////////////////////
function cronInit() {
    var croneditor = cronCreator("0 * * * * *");
    croneditor.initByCronArr();
    croneditor.drawCronByCronArr();
    croneditor.drawEachMinutes();
    croneditor.drawEachHours();
    croneditor.drawEachDays();
    croneditor.drawEachMonths();
    croneditor.drawEachWeek();
    croneditor.drawCronByCronArr();
}

function cronCreator(value) {
    // �섏씠吏� �먮윭濡� �명븳 二쇱꽍 泥섎━ : to.誘쇨퇋��
    let cronValue = value;
    $("#popup_cron_expression").val(value);

    let cronArr = value.split(" ");

    let croneditor = $(".cronDiv").croneditor({
        cronArr: cronArr,
        drawCron: function () {
            let newCron = cronArr.join(" ");
            $("#popup_cron_expression").val(newCron);
        }
    });
    return croneditor;
}



////////////////////////////////////////////////////////////////////////////////////////
// --- �곗씠�� �뚯씠釉� �ㅼ젙 --- //
////////////////////////////////////////////////////////////////////////////////////////
function dataTableLoad() {
    // �곗씠�� �뚯씠釉� 而щ읆 諛� �닿렇猷� 援ъ꽦
    var columnList = [
        { name: "c_id", title: "�쒗뭹(�쒕퉬��) �꾩씠��", data: "c_id", visible: false },
        {
            name: "c_title",
            title: "JOB �대쫫",
            data: "c_title",
            render: function (data, type, row, meta) {
                if (type === "display") {
                    return '<label style="color: #a4c6ff">' + data + "</label>";
                }
                return data;
            },
            className: "dt-body-left",
            visible: true
        },
        {
            name: "c_job_status",
            title: "JOB �곹깭",
            data: "c_job_status",
            render: function (data, type, row, meta) {
                if (type === "display") {
                    return '<label style="color: #a4c6ff">' + data + "</label>";
                }
                return data;
            },
            className: "dt-body-left",
            visible: true
        },
        {
            name: "c_job_last_time",
            title: "JOB 留덉�留� �ㅽ뻾 �쒓컙",
            data: "c_job_last_time",
            render: function (data, type, row, meta) {
                if (type === "display") {
                    return '<label style="color: #a4c6ff">' + data + "</label>";
                }
                return data;
            },
            className: "dt-body-left",
            visible: true
        },
        {
            name: "c_job_next_time",
            title: "JOB �ㅼ쓬 �ㅽ뻾 �쒓컙",
            data: "c_job_next_time",
            render: function (data, type, row, meta) {
                if (type === "display") {
                    return '<label style="color: #a4c6ff">' + data + "</label>";
                }
                return data;
            },
            className: "dt-body-left",
            visible: true
        },
        {
            name: "c_job_duration",
            title: "JOB �됯퇏 �ㅽ뻾 �쒓컙",
            data: "c_job_duration",
            render: function (data, type, row, meta) {
                if (type === "display") {
                    return '<label style="color: #a4c6ff">' + data + "</label>";
                }
                return data;
            },
            className: "dt-body-left",
            visible: true
        }
    ];
    var rowsGroupList = [];
    var columnDefList = [];
    var selectList = {};
    var orderList = [[0, "asc"]];
    var buttonList = [
        "copy",
        "excel",
        "print",
        {
            extend: "csv",
            text: "Export csv",
            charset: "utf-8",
            extension: ".csv",
            fieldSeparator: ",",
            fieldBoundary: "",
            bom: true
        },
        {
            extend: "pdfHtml5",
            orientation: "landscape",
            pageSize: "LEGAL"
        }
    ];

    var jquerySelector = "#schedule_list_table";
    var ajaxUrl = "./mock/scheduleConfig_datatable.json";
    var jsonRoot = "response";
    var isServerSide = false;

    dataTableRef = dataTable_build(
        jquerySelector,
        ajaxUrl,
        jsonRoot,
        columnList,
        rowsGroupList,
        columnDefList,
        selectList,
        orderList,
        buttonList,
        isServerSide
    );

    $("#copychecker").on("click", function () {
        dataTableRef.button(".buttons-copy").trigger();
    });
    $("#printchecker").on("click", function () {
        dataTableRef.button(".buttons-print").trigger();
    });
    $("#csvchecker").on("click", function () {
        dataTableRef.button(".buttons-csv").trigger();
    });
    $("#excelchecker").on("click", function () {
        dataTableRef.button(".buttons-excel").trigger();
    });
    $("#pdfchecker").on("click", function () {
        dataTableRef.button(".buttons-pdf").trigger();
    });
}

// �곗씠�� �뚯씠釉� 援ъ꽦 �댄썑 瑗� 援ы쁽�댁빞 �� 硫붿냼�� : �� �대┃�� �대깽��
function dataTableClick(tempDataTable, selectedData) {
    console.log(selectedData);
}

// �곗씠�� �뚯씠釉� �곗씠�� �뚮뜑留� �댄썑 肄쒕갚 �⑥닔.
function dataTableCallBack(settings, json) {
    console.log("check");
}

function dataTableDrawCallback(tableInfo) {
//	resourceDataTable.columns.adjust();
    console.log(tableInfo);
}


/////////////////////////////////////////////////
// �묒� 洹몃━湲�
/////////////////////////////////////////////////
function drawExcel(target) {
    // 而щ읆 �ㅼ젙
    var columnList = [
        { type: "text", title: "Start Time", wRatio: 0.3},
        { type: "text", title: "End Time", wRatio: 0.3},
        { type: "text", title: "Duration", wRatio: 0.2},
        { type: "text", title: "Status", wRatio: 0.2}
    ];
    // �듭뀡 �ㅼ젙
    var customOption = {
        search: true,
        allowInsertRow: false,
        allowInsertColumn: false,
        updateTable: function(instance, cell, col, row, val, id) {
            cell.style.textAlign = "left";
            cell.style.whiteSpace = "normal";
        }
    };

    SpreadsheetFunctions.setTargetId(target);
    SpreadsheetFunctions.setDefaultTargetRect();

    SpreadsheetFunctions.setColumns(columnList);
    SpreadsheetFunctions.setColumnWidth(SpreadsheetFunctions.getTargetRect("width"));
    SpreadsheetFunctions.setOptions(customOption);
    SpreadsheetFunctions.startObserver();

    $.getJSON('./mock/scheduleConfig_excel.json')
      .done(function(jsonData) {
          let fetchedExcelData = jsonData.map(arr => arr.slice(0, -1)); // map() �� �숆린�⑥닔
          SpreadsheetFunctions.setExcelData(fetchedExcelData);
          SpreadsheetFunctions.drawExcel(SpreadsheetFunctions.getTargetId());
      })
      .fail(function(jqxhr, textStatus, error) {
          console.error("Error loading JSON file: " + textStatus + ", " + error);
      });
}

var SpreadsheetFunctions = (function () {
    let targetId = { "v" : "", "jq" : ""};
    let targetRect = {"width" : 0, "height" : 0};
    let excelData;    // �묒� �곗씠��
    let excelColumns;  // �묒� 而щ읆
    let customOptions;// �묒� 而ㅼ뒪�� �듭뀡�� :: �뺤쓽 �덊븷 寃쎌슦 default


    var setDefaultTargetRect = function () {
        let defaultWidth = $(getTargetId("jq")).width();
        let defaultHeight = $(getTargetId("jq")).height();
        setTargetRect(defaultWidth, defaultHeight);
    };
    var setTargetRect = function(width, height) {
        targetRect.width = width;
        targetRect.height = height;
    };

    var getTargetRect = function (type) {
        if (type === "width") {
            return targetRect.width;
        } else if (type  === "height") {
            return targetRect.height;
        } else {
            return targetRect;
        }
    };

    var setTargetId = function (target) {
        targetId.v = target;
        targetId.jq = "#"+target;
    };

    var getTargetId = function (type) {
        if (type === "jq") {
            return targetId.jq;
        } else {
            return targetId.v;
        }
    };

    var setExcelData = function(data) {
        excelData = data;
    };
    var getExcelData = function () {
        return excelData;
    };
    var setColumns = function(columns) {
        excelColumns = columns;
    };
    var getColumns = function () {
        return excelColumns;
    };

    var setColumnWidth = function (width) {
        if (excelColumns) {
            excelColumns = excelColumns.map(column => ({
                ...column, width: (width * column.wRatio) -1
            }));
        }
    };

    function setColumnWidthAsync(width) {
        return new Promise((resolve) => {
            if (excelColumns) {
                excelColumns = excelColumns.map(column => ({
                    ...column, width: (width * column.wRatio) - 1
                }));
            }
            resolve(); // 而щ읆 �덈퉬 �ㅼ젙�� �꾨즺�� �� resolve �몄텧
        });
    }

    var setOptions = function(options) {
        customOptions = options;
    };
    var getOptions = function() {
        return customOptions ? customOptions : null;
    };


    var resizeObserver = new ResizeObserver(function(entries) {
        for (let entry of entries) {
            setTargetRect(entry.contentRect.width, entry.contentRect.height);
            handleResize(entry.target.id, getTargetRect("width"), getTargetRect("height"));
        }
    });

    // 紐⑤떖�붿냼 �ш린 蹂��� 愿�李�(Observer)
    function startObserver() {
        resizeObserver.observe($(getTargetId("jq"))[0]);
    }

    function handleResize(id, width, height) {
        if (id === getTargetId() && height !== 0) {
            if (excelData) {
                drawResizedExcel(getTargetId());
            } else {
                console.log("Spreadsheet.handleResize :: �묒� �곗씠�� �놁쓬");
            }

        } else {
            console.log("Spreadsheet.handleResize :: id 遺덉씪移� �먮뒗 height 媛� 0 �낅땲��.");
        }
    }

    function drawResizedExcel(target) {
        let $targetId = "#"+target;

        if($($targetId).length > 0 && $($targetId)[0].jexcel) {
            $($targetId)[0].jexcel.destroy();
        }

        setColumnWidthAsync(getTargetRect("width") - 50).then(() => {
            $($targetId).spreadsheet($.extend({}, {
                columns: getColumns(),
                data: getExcelData()
            }, getOptions()));

            let jexcel_content_height = getTargetRect("height") - 40 - 30 - 25;
            $($targetId + " .jexcel_content").css("max-height", jexcel_content_height);
            $($targetId + " .jexcel_content").css("width", "100%");
        });
    }

    function drawExcel(target) {
        let $targetId = "#"+target;

        if($($targetId).length > 0 && $($targetId)[0].jexcel) {
            $($targetId)[0].jexcel.destroy();
        }

        $($targetId).spreadsheet($.extend({}, {
            columns: getColumns(),
            data: getExcelData()
        }, getOptions()));

        let jexcel_content_height = getTargetRect("height") - 40 - 30 - 25;
        $($targetId + " .jexcel_content").css("max-height", jexcel_content_height);
        $($targetId + " .jexcel_content").css("width", "100%");

    }

    return {
        setTargetId,   getTargetId,
        setTargetRect, getTargetRect, setDefaultTargetRect,
        setExcelData,  getExcelData,
        setColumns,    getColumns,   setColumnWidth,
        setOptions,    getOptions,

        startObserver, drawExcel
    };
})();