
export function KeyboardHandler() {
    var self = this;
    // todo fix anyOpenModal 
    self.masterCreateBtn = function () {
        if (anyOpenModal || focusSearchInput)
            return true;
        var cont = self.findActiveSection();
        if (cont["proxyKeyboard"]) {
            cont.proxyKeyboard("create");
        } else if (cont["createBtn"] !== null && cont["createBtn"] !== undefined && resDomain !== "Tree") {
            if (cont["viscreate"] !== null && cont["viscreate"] !== undefined && cont.viscreate())
                cont.createBtn();
        }
    };
    self.masterEditBtn = function () {
        if (anyOpenModal || focusSearchInput)
            return true;
        var cont = self.findActiveSection();
        if (cont["proxyKeyboard"]) {
            cont.proxyKeyboard("edit");
        } else if (cont["editBtn"] !== null && cont["editBtn"] !== undefined && resDomain !== "Tree") {
            if (cont["isSelectedRecord"] !== null && cont["isSelectedRecord"] !== undefined)
                cont.editBtn();
        }
    };
    self.masterDeleteBtn = function () {
        if (anyOpenModal || focusSearchInput)
            return true;
        var cont = self.findActiveSection();
        if (cont["proxyKeyboard"]) {
            cont.proxyKeyboard("delete");
        } else if (cont["deleteBtn"] !== null && cont["deleteBtn"] !== undefined && resDomain !== "Tree") {
            if (cont["visdelete"] !== null && cont["visdelete"] !== undefined && cont.visdelete())
                cont.deleteBtn();
        } else if (cont["deleteListBtn"] !== null && cont["deleteListBtn"] !== undefined && resDomain !== "Tree") {
            if (cont["hasSelectedRecord"] !== null &&
                cont["hasSelectedRecord"] !== undefined &&
                cont.hasSelectedRecord())
                cont.deleteListBtn();
        }
    };
    self.masterRefreshBtn = function () {
        if (anyOpenModal || focusSearchInput)
            return true;
        var cont = self.findActiveSection();
        if (cont["proxyKeyboard"]) {
            cont.proxyKeyboard("refresh");
        } else if (cont["refreshTable"] !== null && cont["refreshTable"] !== undefined) {
            cont.refreshTable();
        }
    };
    self.masterHelpBtn = function (shiftKey) {
        if (anyOpenModal || focusSearchInput)
            return true;
        _h.kocnx().getHelpData(undefined, undefined, "", function (data) {
            if (data) {
                var model = new HelpViewModel();
                model.fillModel(data);
                _h.kocnx().helpModal(model);
                _h.kocnx().showHelp(true);
            }
        });
    }
    self.masterUpKey = function (e, shiftKey) {
        var cont = self.findActiveSection(e, shiftKey);
        if (cont["up"] !== null && cont["up"] !== undefined) {
            cont.up(shiftKey);
        }
    }
    self.masterDownKey = function (e, shiftKey) {
        var cont = self.findActiveSection(e, shiftKey);
        if (cont["down"] !== null && cont["down"] !== undefined) {
            cont.down(shiftKey);
        }
    }
    self.masterRightKey = function (e, shiftKey) {
        var cont = self.findActiveSection(e, shiftKey);
        if (cont["right"] !== null && cont["right"] !== undefined) {
            return cont.right(shiftKey);
        }
        return true;
    }
    self.masterLeftKey = function (e, shiftKey) {
        var cont = self.findActiveSection(e, shiftKey);
        if (cont["left"] !== null && cont["left"] !== undefined) {
            return cont.left(shiftKey);
        }
        return true;
    }
    self.findActiveSection = function () {
        var tables = $(".ko-tbl:visible");
        var openModal = $(".modal.in");
        if (openModal.length) {
            tables = openModal.find(".ko-tbl:visible");
        }

        var viewModel, master, detail;
        switch (tables.length) {
            case 1:
                return ko.contextFor(tables[0]).$data;
            case 2:
                if ($("#Tree-t").hasClass("active")) {
                    for (var b = 0; b < tables.length; b++) {
                        if ($(tables[b]).hasClass("tree-tbl"))
                            return ko.contextFor(tables[b]).$data;
                    }
                } else {
                    for (var j = 0; j < tables.length; j++) {
                        if ($(tables[j]).hasClass("ko-tbl-master") && !activeSection ||
                            activeSection === "master") {
                            return ko.contextFor(tables[j]).$data;
                        }

                        if ($(tables[j]).hasClass("ko-tbl-child") && window.activeSection && window.activeSection === "detail") {
                            return ko.contextFor(tables[j]).$data;
                        }
                        if ($(tables[j]).hasClass("ko-tbl-dyninfo"))
                            return ko.contextFor(tables[j]).$data;
                    }
                }
                break;
            case 3:
                if ($("#Period-t").hasClass("active") || $("#Tree-t").hasClass("active")) {
                    for (var i = 0; i < tables.length; i++) {
                        if ($(tables[i]).hasClass("period-tbl") || $(tables[i]).hasClass("tree-tbl"))
                            return ko.contextFor(tables[i]).$data;
                    }
                }
                break;
            case 4:

                break;
        }
    }
}



$(document).on("click", ".master-section", function (evt) {
    activeSection = "master";
    evt.preventDefault();
});
$(document).on("click", ".detail-section", function (evt) {
    activeSection = "detail";
    evt.preventDefault();
});
var pressed = false;
$(document).on("keydown",
    function (evt) {
        if (anyOpenModal ||
            focusSearchInput ||
            (resDomain === "TableTemplate" && resSecondDomain === "editor") ||
            $(evt.target).hasClass("key-on") ||
            resSecondDomain === 'pageeditor')
            return true;
        if ($(evt.target).parent() && $(evt.target).parent().hasClass("selectize-input"))
            return true;

        var res;
        var context = _h.kocnx();
        switch (evt.keyCode) {
            case 37:
                res = context.keysHandler().masterLeftKey(evt, evt.shiftKey);
                return res;
            case 38:
                res = context.keysHandler().masterUpKey(evt, evt.shiftKey);
                return res;
            case 39:
                res = context.keysHandler().masterRightKey(evt, evt.shiftKey);
                return res;
            case 40:
                res = context.keysHandler().masterDownKey(evt, evt.shiftKey);
                return res;
            case 67:
                pressed = true;
                if (evt.ctrlKey) {
                    if ($("#TableTemplate-t").hasClass("active"))
                        context.ttvm().copyClipboard();
                    else
                        return true;
                } else {
                    return true;
                }
                break;
            case 68:
                if (evt.shiftKey)
                    context.keysHandler().masterDeleteBtn();
                break;
            case 69:
                if (evt.shiftKey)
                    context.keysHandler().masterEditBtn();
                break;
            case 78:
                if (evt.shiftKey)
                    context.keysHandler().masterCreateBtn();
                break;
            case 82:
                if (evt.shiftKey)
                    context.keysHandler().masterRefreshBtn();
                break;
            case 186:
                if (evt.shiftKey && evt.ctrlKey)
                    context.securityConfigBtn();
                break;
        }
        evt.stopPropagation();
        evt.preventDefault();
    });
$(document).on("keyup", function (evt) {
    if (evt.which === 67) { // e
        pressed = false;
    }
});

$(document).on("click", ".ko-tbl, #br_Table", function (evt) {
    if (evt.ctrlKey && pressed) {
        evt.preventDefault();
        const target = evt.target;
        var oldColor = evt.target.style.color;
        evt.target.style.color = "red";
        var temp = "";
        if ($(target).hasClass("table-node-code"))
            temp = target.innerText.replace("(", "").replace(")", "");
        else
            temp = target.innerText;
        if (window.navigator.clipboard) {
            window.navigator.clipboard.writeText(temp);
        } else {
            var $temp = $("<input>");
            $("body").append($temp);
            if ($(target).hasClass("table-node-code"))
                $temp.val(target.innerText.replace("(", "").replace(")", "")).select();
            else
                $temp.val(target.innerText).select();
            document.execCommand("copy");
        }
        setTimeout(function () {
            evt.target.style.color = oldColor;
        }, 350);
    }
});

$(document).on("dblclick", ".ko-tbl tr", function (evt) {
    if (!$(evt.currentTarget).hasClass("row-group"))
        _h.kocnx().keysHandler().masterEditBtn();
});
