LeoAltholicToolbarUI.items = {
    INVENTORY = 1,
    RIDING = 2,
    RESEARCH = 3,
    CHECKLIST = 4
}

function LeoAltholicToolbarUI.normalizeSettings()
    if not LeoAltholic.globalData.toolbar then LeoAltholic.globalData.toolbar = {} end
    if not LeoAltholic.globalData.settings.toolbar then LeoAltholic.globalData.settings.toolbar = {} end
end

function LeoAltholicToolbarUI.SetPosition(left, top)
    LeoAltholic.globalData.toolbar.position = {
        left = left,
        top = top
    }
end
function LeoAltholicToolbarUI.GetPosition()
    return LeoAltholic.globalData.toolbar.position or { left = 100; top = 200; }
end

function LeoAltholicToolbarUI.SetEnabled(value)
    LeoAltholic.globalData.settings.toolbar.enabled = value
    LeoAltholicToolbarUI.RestorePosition()
end
function LeoAltholicToolbarUI.IsEnabled()
    if LeoAltholic.globalData.settings.toolbar.enabled == nil then LeoAltholic.globalData.settings.toolbar.enabled = false end
    return LeoAltholic.globalData.settings.toolbar.enabled
end

function LeoAltholicToolbarUI.SetBumpCompass(value)
    LeoAltholic.globalData.settings.toolbar.bumpCompass = value
    LeoAltholicToolbarUI.BumpCompass()
end
function LeoAltholicToolbarUI.GetBumpCompass()
    if LeoAltholic.globalData.settings.toolbar.bumpCompass == nil then LeoAltholic.globalData.settings.toolbar.bumpCompass = false end
    return LeoAltholic.globalData.settings.toolbar.bumpCompass
end

function LeoAltholicToolbarUI.SetItem(item, value)
    if not LeoAltholic.globalData.settings.toolbar.items then LeoAltholic.globalData.settings.toolbar.items = {} end
    LeoAltholic.globalData.settings.toolbar.items[item] = value
    LeoAltholicToolbarUI.update()
end
function LeoAltholicToolbarUI.GetItem(item)
    if not LeoAltholic.globalData.settings.toolbar.items then LeoAltholic.globalData.settings.toolbar.items = {} end
    if LeoAltholic.globalData.settings.toolbar.items[item] == nil then LeoAltholic.globalData.settings.toolbar.items[item] = true end
    return LeoAltholic.globalData.settings.toolbar.items[item]
end

local function checkCenter()
    if LeoAltholicToolbar:GetTop() <= 60 then
        local x = LeoAltholicToolbar:GetCenter()
        local guiRootX = GuiRoot:GetCenter()
        if x ~= guiRootX then
            x = LeoAltholicToolbar:GetLeft() + (guiRootX - x)
            LeoAltholicToolbar:ClearAnchors()
            LeoAltholicToolbar:SetAnchor(TOPLEFT, GuiRoot, TOPLEFT, x, LeoAltholicToolbar:GetTop())
            LeoAltholicToolbarUI.SetPosition(x, LeoAltholicToolbar:GetTop())
        end
    end
end

function LeoAltholicToolbarUI.OnWindowMoveStop()
    checkCenter()
    LeoAltholicToolbarUI.SetPosition(LeoAltholicToolbar:GetLeft(), LeoAltholicToolbar:GetTop())
end

function LeoAltholicToolbarUI.RestorePosition()
    local position = LeoAltholicToolbarUI.GetPosition()
    local left = position.left
    local top = position.top

    LeoAltholicToolbar:ClearAnchors()
    LeoAltholicToolbar:SetAnchor(TOPLEFT, GuiRoot, TOPLEFT, left, top)
    if LeoAltholicToolbarUI.IsEnabled() then
        LeoAltholicToolbar:SetHidden(false)
    else
        LeoAltholicToolbar:SetHidden(true)
    end
end

function LeoAltholicToolbarUI.BumpCompass()
    local hasWykkydsToolbar = false
    if WYK_Toolbar and wykkydsToolbar then hasWykkydsToolbar = true end
    if not hasWykkydsToolbar and LeoAltholicToolbarUI.IsEnabled() and LeoAltholicToolbarUI.GetBumpCompass() then
        if LeoAltholicToolbar:GetTop() <= 60 then
            if math.floor(ZO_CompassFrame:GetTop()) ~= math.floor(LeoAltholicToolbar:GetTop()) + 60 then
                ZO_CompassFrame:ClearAnchors()
                ZO_CompassFrame:SetAnchor( TOP, GuiRoot, TOP, 0, LeoAltholicToolbar:GetTop() + 60)
                ZO_TargetUnitFramereticleover:ClearAnchors()
                ZO_TargetUnitFramereticleover:SetAnchor( TOP, GuiRoot, TOP, 0, LeoAltholicToolbar:GetTop() + 110)
            end
        elseif ZO_CompassFrame:GetTop() ~= 40 then
            ZO_CompassFrame:ClearAnchors()
            ZO_CompassFrame:SetAnchor( TOP, GuiRoot, TOP, 0, 40 )
            ZO_TargetUnitFramereticleover:ClearAnchors()
            ZO_TargetUnitFramereticleover:SetAnchor( TOP, GuiRoot, TOP, 0, 88 )
        end
    end
end

local function addLine(tooltip, text, color)
    if not color then color = ZO_SELECTED_TEXT end
    local r, g, b = color:UnpackRGB()
    tooltip:AddLine(text, "LeoAltholicNormalFont", r, g, b, CENTER, MODIFY_TEXT_TYPE_NONE, TEXT_ALIGN_LEFT, true)
end

local function hasExpiredQueue()
    for x,data in pairs(LeoAltholic.timerQueue) do
        if GetDiffBetweenTimeStamps(data.time, GetTimeStamp()) <= 0 then
            return true
        end
    end
    return false
end

function LeoAltholicUI.TooltipWarning(control, visible)

    if visible and hasExpiredQueue() then
        if not parent then parent = control end

        InitializeTooltip(InformationTooltip, control, TOPLEFT, -100, 40, TOPLEFT)

        for x,data in pairs(LeoAltholic.timerQueue) do
            if GetDiffBetweenTimeStamps(data.time, GetTimeStamp()) <= 0 then
                addLine(InformationTooltip, data.info)
            end
        end

        InformationTooltip:SetHidden(false)
        InformationTooltipTopLevel:BringWindowToTop()
    else
        ClearTooltip(InformationTooltip)
        InformationTooltip:SetHidden(true)
    end
end


function LeoAltholicToolbarUI.update()

    if not LeoAltholicToolbarUI.IsEnabled() then return end

    LeoAltholicToolbarUI.BumpCompass()

    local char = LeoAltholic.GetMyself()
    local toolbar = WINDOW_MANAGER:GetControlByName("LeoAltholicToolbar")

    local warning = GetControl(toolbar, "WarningIcon")
    if hasExpiredQueue() then
        warning:SetHidden(false)
        local line = GetControl(toolbar, "WarningLine")
        line:SetHidden(false)
        line:SetAnchor(TOPLEFT, warning, TOPLEFT, 2, 0)
        line:SetAnchor(BOTTOMRIGHT, warning, BOTTOMLEFT, 2, 0)
    else
        warning:SetHidden(true)
    end

    local offsetX = 0
    local width = 120
    local numSections = 0
    local totalWidth = 0

    local line
    local label = GetControl(toolbar, "Inventory")
    local texture = GetControl(toolbar, "InventoryTexture")
    label:SetHidden(true)
    texture:SetHidden(true)
    if LeoAltholicToolbarUI.GetItem(LeoAltholicToolbarUI.items.INVENTORY) then
        local color = '|c' .. LeoAltholic.color.hex.green
        if char.inventory.free <= 25 then color = '|c'..LeoAltholic.color.hex.yellow end
        if char.inventory.free <= 10 then color = '|c'..LeoAltholic.color.hex.red end
        label:SetText(color .. char.inventory.used .. "|r / " .. char.inventory.size)
        label:SetHidden(false)
        texture:SetHidden(false)
        texture:SetAnchor(TOPLEFT, toolbar, TOPLEFT, offsetX, 0)
        offsetX = offsetX + 100
        numSections = numSections + 1
        totalWidth = totalWidth + 105
    end

    line = GetControl(toolbar, "RidingLine")
    label = GetControl(toolbar, "Riding")
    texture = GetControl(toolbar, "RidingTexture")
    line:SetHidden(true)
    label:SetHidden(true)
    texture:SetHidden(true)
    if LeoAltholicToolbarUI.GetItem(LeoAltholicToolbarUI.items.RIDING) and
            (char.attributes.riding.speed < char.attributes.riding.speedMax or
            char.attributes.riding.stamina < char.attributes.riding.staminaMax or
            char.attributes.riding.capacity < char.attributes.riding.capacityMax) then
        label:SetText(LeoAltholic.FormatTime(char.attributes.riding.time - GetTimeStamp(), true, true))
        label:SetHidden(false)
        texture:SetHidden(false)
        line:SetHidden(false)
        texture:SetAnchor(TOPLEFT, toolbar, TOPLEFT, offsetX, 0)
        line:SetAnchor(TOPLEFT, texture, TOPLEFT, 2, 0)
        line:SetAnchor(BOTTOMRIGHT, texture, BOTTOMLEFT, 2, 0)
        offsetX = offsetX + 100
        numSections = numSections + 1
        totalWidth = totalWidth + 130
    end

    line = GetControl(toolbar, "CraftLine")
    line:SetHidden(true)
    for _,craft in pairs(LeoAltholic.craftResearch) do
        label = GetControl(toolbar, "Craft"..craft)
        texture = GetControl(toolbar, "Craft"..craft.."Texture")
        label:SetHidden(true)
        texture:SetHidden(true)
    end
    if LeoAltholicToolbarUI.GetItem(LeoAltholicToolbarUI.items.RESEARCH) then
        local firstTexture
        for _,craft in pairs(LeoAltholic.craftResearch) do
            if LeoAltholic.HasStillResearchFor(craft) then
                label = GetControl(toolbar, "Craft"..craft)
                texture = GetControl(toolbar, "Craft"..craft.."Texture")
                if firstTexture == nil then
                    firstTexture = texture
                end
                local researching, total, lowest = LeoAltholic.GetResearchCounters(craft)
                local missing = LeoAltholic.GetNumMissingTraitsFor(craft)
                local color = '|c'..LeoAltholic.color.hex.green
                if researching < total and researching < missing then
                    color = '|c'..LeoAltholic.color.hex.red
                end
                label:SetText(color .. researching .. '/' .. total .. '|r ' .. LeoAltholic.FormatTime(lowest - GetTimeStamp(), true, true))
                label:SetHidden(false)
                texture:SetHidden(false)
                texture:SetAnchor(TOPLEFT, toolbar, TOPLEFT, offsetX, 0)
                label:SetAnchor(TOPLEFT, texture, TOPRIGHT, 2, 0)
                offsetX = offsetX + width
                numSections = numSections + 1
                totalWidth = totalWidth + 120
            end
        end
        if firstTexture ~= nil then
            line:SetHidden(false)
            line:SetAnchor(TOPLEFT, firstTexture, TOPLEFT, 2, 0)
            line:SetAnchor(BOTTOMRIGHT, firstTexture, BOTTOMLEFT, 2, 0)
        end
    end

    local checklistOffsetX = 0
    local checklist = GetControl(toolbar, "Checklist")
    local shownChecklist = false
    if LeoAltholicToolbarUI.GetItem(LeoAltholicToolbarUI.items.CHECKLIST) then
        checklist:SetAnchor(TOPLEFT, toolbar, TOPLEFT, offsetX, 0)
        checklist:SetHidden(false)
        local icon
        for _, craft in pairs(LeoAltholic.allCrafts) do
            icon = GetControl(checklist, "Craft"..craft.."Icon")
            if LeoAltholicChecklistUI.GetCraft(craft) then

                local isDone = false
                for _, writ in pairs(char.quests.writs) do
                    if craft == writ.craft then
                        if writ.lastDone ~= nil and LeoAltholic.IsAfterReset(writ.lastDone) then
                            isDone = true
                        elseif writ.lastPreDeliver ~= nil and LeoAltholic.IsAfterReset(writ.lastPreDeliver) then
                            icon:SetColor(1,1,0,1)
                        elseif writ.lastUpdated ~= nil and LeoAltholic.IsAfterReset(writ.lastUpdated) then
                            icon:SetColor(1,0.8,0,1)
                        elseif writ.lastStarted ~= nil and LeoAltholic.IsAfterReset(writ.lastStarted) then
                            icon:SetColor(0.8,0.8,0.8,1)
                        else
                            icon:SetColor(1,0,0,1)
                        end

                        if not isDone then
                            shownChecklist = true
                            icon:SetHidden(false)
                            icon:SetAnchor(TOPLEFT, checklist, TOPLEFT, checklistOffsetX, -2)
                            checklistOffsetX = checklistOffsetX + 35
                        else
                            icon:SetHidden(true)
                        end
                    end
                end
            else
                icon:SetHidden(true)
            end
        end

        icon = GetControl(checklist, "RidingIcon")
        icon:SetHidden(true)
        if char.attributes.riding.time - GetTimeStamp() < 0 then
            shownChecklist = true
            icon:SetHidden(false)
            icon:SetColor(1,0,0,1)
            icon:SetAnchor(TOPLEFT, checklist, TOPLEFT, checklistOffsetX, -4)
            checklistOffsetX = checklistOffsetX + 35
        end
    else
        checklist:SetHidden(true)
    end
    if shownChecklist then
        line = GetControl(toolbar, "ChecklistLine")
        line:SetHidden(false)
        line:SetAnchor(TOPLEFT, checklist, TOPLEFT, 2, 0)
        line:SetAnchor(BOTTOMRIGHT, checklist, BOTTOMLEFT, 2, 0)
    end
    totalWidth = totalWidth + checklistOffsetX

    if numSections > 0 then
        toolbar:SetWidth(totalWidth)
        GetControl(toolbar, "BG"):SetWidth(totalWidth)
        checkCenter()
    else
        toolbar:SetHidden(true)
    end
end