//====UI Constants====//
const IS_WINDOWS            = navigator.appVersion.indexOf("Win") != -1;
const OPTIONS_MENU_WIDTH    = 150;

//====Omnis Data Constants====//
const ID          = 1;
const DESCRIPTION = 2;
const ICON        = 3;
const SELECTED    = 4;
const DISABLED    = 5;
const EXPLODED    = 6;
const HIDDEN      = 7;

//====Scroll Constants====//
const CONTINUOUS_SCROLL_SPEED    = 4000;
const SCROLL_LEFT                = -1;
const SCROLL_RIGHT               = 1;

jOmnis.callbackObject = {
    tabBar: null,
    tabs:   null,

    getLeft: function(tab) {
        if (tab.offsetLeft + tab.clientWidth - this.tabBar.scrollLeft - OPTIONS_MENU_WIDTH < 0) {
            if (tab.getBoundingClientRect().left < 0) return OPTIONS_MENU_WIDTH - (IS_WINDOWS ? 8 : 0);
            return tab.offsetLeft + OPTIONS_MENU_WIDTH - this.tabBar.scrollLeft - (IS_WINDOWS ? 8 : 0);
        }
        return tab.offsetLeft + tab.clientWidth - this.tabBar.scrollLeft - (IS_WINDOWS ? 7 : 0);
    },
    getSelectedTabPosition: function() {
        var selectedTabPosition = 0;
        var selectedTabIndex = this.tabs.findIndex(x => x.selected);

        for (var i = 0; i < selectedTabIndex; i++) selectedTabPosition += document.getElementById(this.tabs[i].id).offsetWidth;
        return selectedTabPosition;
    },
    getSequence: function() {
        var tabsInOrder = [];
        var tabElements = this.tabBar.getElementsByTagName("li");
        for (var i = 0; i < tabElements.length; i++) {
            tabElements[i].omnisLine = i + 1;
            tabsInOrder.push(tabElements[i].id);
        }

        return tabsInOrder.toString();        
    },
    highlightSelectedTab: function(tabID) {
        this.tabs.find(x => x.id == tabID)["selected"] = true;

        document.getElementById(tabID).style.backgroundColor = IS_WINDOWS ? "#ffffff" : "#ececec";
        document.getElementById(tabID).style.borderBottom    = IS_WINDOWS ? "1px solid #ffffff" : "1px solid #ececec";
    },
    loadTabBar: function() {
        for (var i = 0; i < this.tabs.length; i++) {
            var tab = document.createElement("LI");
            tab.omnisLine = i + 1;
            tab.id = this.tabs[i]["id"];
            tab.className = "tab";
            tab.disabled = this.tabs[i]["disabled"];
            tab.onclick = function() {
                if (!this.disabled) jOmnis.callbackObject.openTab(this)
            };

            var description = '<div class="description">' 

            tab.innerHTML += "<div class='padding'>&nbsp;</div>"
            tab.innerHTML += this.tabs[i]["icon"].length > 0 ? `<img src='../../iconsets/suran/${this.tabs[i]["icon"]}'>` : "";
            tab.innerHTML += description +
            this.tabs[i]["description"] + `</div>
            <div class='options' onclick='jOmnis.callbackObject.optionsClicked(this.parentElement)'>⋮</div>`;

            this.tabBar.appendChild(tab);
            if (this.tabs[i]["selected"]) this.highlightSelectedTab(this.tabs[i]["id"]);
        }
    },
    openTab: function(tab) {
        var previousTab = this.tabs.find(x => x.selected);
        if (previousTab.id != tab.id) {
            previousTab["selected"] = false;

            document.getElementById(previousTab["id"]).style.background   = IS_WINDOWS ? "#f0f0f0" : "#e2e2e2";
            document.getElementById(previousTab["id"]).style.borderBottom = IS_WINDOWS ? "1px solid #f0f0f0" : "1px solid #cfcfcf";
            this.highlightSelectedTab(tab.id);

            jOmnis.sendClickEvent(this.omnisGetCurrentLine());
        }
    },
    optionsClicked: function(tab) {
        if (!tab.disabled) this.openTab(tab);

        jOmnis.sendControlEvent({
            "Description": "options",
            "Left": jOmnis.callbackObject.getLeft(tab),
            "Tab_ID": tab.id
        });
    },
    toggleNavButtons: function(windowWidth) {
        var tabBarWidth = 0;
        $(".tab").each(function(index) {
            tabBarWidth += parseInt($(this).outerWidth(), 10);
        });

        if(tabBarWidth > windowWidth) {
            this.tabBar.style.width = "calc(100% - 60px)";
            this.tabBar.style.marginLeft = "30px";
            document.getElementById("left").style.display = "inline-block";
            document.getElementById("right").style.display = "inline-block";
        } else {
            this.tabBar.style.width = "100%";
            this.tabBar.style.marginLeft = "0";
            document.getElementById("left").style.display = "none";
            document.getElementById("right").style.display = "none";
        }
    },

    omnisGetCurrentLine: function() {
        return document.getElementById(this.tabs.find(x => x.selected)["id"]).omnisLine;
    },
    omnisOnLoad: function() {
        this.tabBar = document.getElementById("tab-bar");
        this.tabs = [];
        this.dataSet = false;
    },
    omnisSetData: function(tabs) {
        this.tabBar.innerHTML = "";
        this.tabs = [];

        if (tabs instanceof omnis_list && tabs.getRowCount()>0) {
            for (var i = 0; i < tabs.getRowCount(); i++) {
                if (!(tabs.getData(EXPLODED, i + 1)|tabs.getData(HIDDEN, i + 1)|tabs.getData(DISABLED, i + 1))) {
                    this.tabs.push({
                        id:          tabs.getData(ID, i + 1),
                        description: tabs.getData(DESCRIPTION, i + 1),
                        icon:        tabs.getData(ICON, i + 1),
                        selected:    tabs.getData(SELECTED, i + 1)
                    });
                }
            }

            this.loadTabBar();
            computeTotalTabsWidth();
        }
    }
};

function computeTotalTabsWidth() {
    totalTabsWidth = 0;
    $(".tab").each(function(index) {
        totalTabsWidth += parseInt($(this).outerWidth(), 10);
    });
}
function continuousScroll(direction) {
    $("#tab-bar").animate(
        {scrollLeft: direction * totalTabsWidth},
        CONTINUOUS_SCROLL_SPEED,
        "linear"
    );
}
function scrollToSelectedTab() {
    $("#tab-bar").animate(
        {scrollLeft: jOmnis.callbackObject.getSelectedTabPosition()},
        0,
        "linear"
    );
}

$( function () {
    $( "#tab-bar" ).sortable({
        axis: "x",
        containment: "window",
        update: function(event, ui) {
            jOmnis.sendControlEvent({
                "Description": "rearrange",
                "Order": jOmnis.callbackObject.getSequence()
            });
        }
    });
    $( "#tab-bar" ).disableSelection();
} );

$("#right").mousedown((e) => {
    if (e.shiftKey) {
        scrollToSelectedTab();
        return;
    }
    continuousScroll(SCROLL_RIGHT);
}).mouseup(() => {
    $("#tab-bar").stop();
});

$("#left").mousedown((e) => {
    if (e.shiftKey) {
        scrollToSelectedTab();
        return;
    }
    continuousScroll(SCROLL_LEFT);
}).mouseup(() => {
    $("#tab-bar").stop();
});