LeoAltholic.hidden = true
LeoAltholic.listingInventoryFor = 0

function LeoAltholic:OnWindowMoveStop()
    LeoAltholic.savedVariables.position = {
        left = LeoAltholicWindow:GetLeft(),
        top = LeoAltholicWindow:GetTop()
    }
end

function LeoAltholic:isHidden()
    return LeoAltholic.hidden
end

function LeoAltholic.RestorePosition()
    local position = LeoAltholic.savedVariables.position or { left = 100; top = 100; }
    local left = position.left
    local top = position.top

    LeoAltholicWindow:ClearAnchors()
    LeoAltholicWindow:SetAnchor(TOPLEFT, GuiRoot, TOPLEFT, left, top)
end

function LeoAltholic.ChangeInventoryUI(bagId)
    LeoAltholic.ShowInventoryUI(LeoAltholic.listingInventoryFor, bagId)
end

function LeoAltholic.ShowInventoryUI(charName, bagId)
    LeoAltholic.listingInventoryFor = charName
    SCENE_MANAGER:ShowTopLevel(LeoAltholicInventoryWindow)
    LeoAltholicInventoryWindow:SetHidden(false)
    local char = LeoAltholic.GetCharByName(charName)
    local sc = WINDOW_MANAGER:GetControlByName("LeoAltholicInventoryWindowListScrollChild")
    sc:SetHidden(false)

    local i = 1
    for x = 1, sc:GetNumChildren() do
        sc:GetChild(x):SetHidden(true)
    end
    for _, item in pairs(LeoAltholic.GetItems(char, bagId)) do
        local row = WINDOW_MANAGER:GetControlByName("LeoAltholicInventoryWindowRow" .. i)
        if not row then
            row = CreateControlFromVirtual("LeoAltholicInventoryWindowRow" .. i, sc, "LeoAltholicInventoryTemplate")
        end
        local control = row:GetNamedChild("Item")
        control:SetHidden(false)
        local qty = ""
        if item.count > 1 then
            qty = " (" .. item.count ..")"
        end
        control:SetText(zo_iconFormat(GetItemLinkIcon(item.link), 25, 25) .." ".. item.link .. qty)
        control:SetHandler("OnMouseEnter",
                function(self)
                    InitializeTooltip(LeoAltholicItemToolTip, LeoAltholicInventoryWindow, TOPLEFT, -450, 50, TOPLEFT)
                    LeoAltholicItemToolTip:SetLink(item.link)
                end
        )
        control:SetHandler("OnMouseExit",
                function(self)
                    ClearTooltip(LeoAltholicItemToolTip)
                end
        )
        row:SetAnchor(TOPLEFT, sc, TOPLEFT, 2, (i - 1) * 30)
        row:SetHidden(false)
        i = i + 1
    end
    sc:SetHeight(i * 30)
end

function LeoAltholic.HideInventoryUI()
    SCENE_MANAGER:HideTopLevel(LeoAltholicInventoryWindow)
    LeoAltholicInventoryWindow:SetHidden(true)
end

function LeoAltholic.ShowUI()
    SCENE_MANAGER:ShowTopLevel(LeoAltholicWindow)
    LeoAltholicWindow:SetHidden(false)
    LeoAltholic.hidden = false;
    LeoAltholic.ShowTab(LeoAltholic.savedVariables.activeTab or "Bio")
end

function LeoAltholic.HideUI()
    SCENE_MANAGER:HideTopLevel(LeoAltholicWindow)
    LeoAltholicWindow:SetHidden(true)
    LeoAltholic.HideInventoryUI()
    LeoAltholic.hidden = true;
end

function LeoAltholic.ToggleUI()
    SCENE_MANAGER:ToggleTopLevel(LeoAltholicWindow)
    if LeoAltholic:isHidden() then
        LeoAltholic.ShowUI()
    else
        LeoAltholic.HideUI()
    end
end

function LeoAltholic.ShowTab(tab)
    LeoAltholic.savedVariables.activeTab = tab
    LeoAltholicWindowTitle:SetText(LeoAltholic.displayName .. " v" .. LeoAltholic.version .. " - " .. tab)
    local control
    for _,panel in ipairs(LeoAltholic.panelList) do
        control = WINDOW_MANAGER:GetControlByName('LeoAltholicWindow' .. panel .. 'Panel')
        control:SetHidden(true)
    end
    control = WINDOW_MANAGER:GetControlByName("LeoAltholicWindow" .. tab .. "Panel")
    control:SetHidden(false)
end

function LeoAltholic.GetTime(seconds)
    if seconds and seconds > 0 then
        local ss = seconds % 60
        local mm = math.floor(seconds / 60)
        local hh = math.floor(mm / 60)
        mm = mm % 60
        local dn = math.floor(hh / 24)
        local result = ''
        if dn > 0 then result = tostring(dn) .. GetString(LEOALT_D) .." " .. tostring (hh - (dn*24)) .. GetString(LEOALT_H)
        elseif hh > 0 then result = tostring (hh) .. GetString(LEOALT_H) .." " .. tostring (mm) .. GetString(LEOALT_M)
        elseif mm > 0 then result = mm .. GetString(LEOALT_M) .." " .. ss .. GetString(LEOALT_S)
        end
        return result
    else return '|cFF4020'..GetString(LEOALT_FINISHED)..'|r' end
end

local function formatNumber(amount)
    if amount == nil then return nil; end
    if type(amount) == "string" then amount = tonumber( amount ) end
    if type(amount) ~= "number" then return amount; end
    if amount < 1000 then return amount; end
    return FormatIntegerWithDigitGrouping( amount, GetString( SI_DIGIT_GROUP_SEPARATOR ) )
end

function LeoAltholicUI.InitPanels()
    LeoAltholicUI.bioList = LeoAltholicBioList:New(LeoAltholicWindowBioPanelListScroll)
    LeoAltholicUI.bioList:RefreshData()

    LeoAltholicUI.statsList = LeoAltholicStatsList:New(LeoAltholicWindowStatsPanelListScroll)
    LeoAltholicUI.statsList:RefreshData()

    LeoAltholicUI.championList = LeoAltholicChampionList:New(LeoAltholicWindowChampionPanelListScroll)
    LeoAltholicUI.championList:RefreshData()

    LeoAltholicUI.skillsList = LeoAltholicSkillsList:New(LeoAltholicWindowSkillsPanelListScroll)
    LeoAltholicUI.skillsList:RefreshData()

    LeoAltholicUI.skills2List = LeoAltholicSkills2List:New(LeoAltholicWindowSkills2PanelListScroll)
    LeoAltholicUI.skills2List:RefreshData()

    LeoAltholicUI.writsList = LeoAltholicWritsList:New(LeoAltholicWindowWritsPanelListScroll)
    LeoAltholicUI.writsList:RefreshData()

    LeoAltholicUI.invList = LeoAltholicInventoryList:New(LeoAltholicWindowInventoryPanelListScroll)
    LeoAltholicUI.invList:RefreshData()

    LeoAltholicUI.researchList = LeoAltholicResearchList:New(LeoAltholicWindowResearchPanelListScroll)
    LeoAltholicUI.researchList:RefreshData()

    LeoAltholicUI.InitTrackedPanel()
end

function LeoAltholic.DisplayCharacterFrames()
    local control
    for _,panel in ipairs(LeoAltholic.panelList) do
        if panel ~= "Writs" then
            control = WINDOW_MANAGER:GetControlByName('LeoAltholicWindow' .. panel .. 'PanelScrollChild')
            control:SetHeight(#LeoAltholic.GetCharacters() * 109)
        end
    end
    control = WINDOW_MANAGER:GetControlByName('LeoAltholicWindowTrackedPanelScrollChild')
    control:SetHeight(#LeoAltholic.GetCharacters() * 169)
    control = WINDOW_MANAGER:GetControlByName('LeoAltholicWindowResearchPanelScrollChild')
    control:SetHeight(#LeoAltholic.GetCharacters() * 262)
    control = WINDOW_MANAGER:GetControlByName('LeoAltholicWindowSkillsPanelScrollChild')
    control:SetHeight(#LeoAltholic.GetCharacters() * 522)

    for x,char in pairs(LeoAltholic.GetCharacters()) do

        for _,panel in ipairs(LeoAltholic.panelList) do
            local row = WINDOW_MANAGER:GetControlByName('LeoAltholic' .. panel .. 'Row'..x)

            control = row:GetNamedChild("Name")
            control:SetText(char.bio.name)

            if panel ~= "Writs" then
                control = row:GetNamedChild("Alliance")
                local icon = ZO_GetAllianceIcon(char.bio.alliance.id)
                control:SetText("|cF1FF77|t50:90:" .. icon .. "|t|r ")
                control.data = char.bio.alliance.name

                control = row:GetNamedChild("RaceClass")
                control:SetText(char.bio.race .. " " .. char.bio.class)
            end
        end

        if char.quests ~= nil and char.quests.tracked ~= nil then
            row = WINDOW_MANAGER:GetControlByName('LeoAltholicTrackedRow'..x)
            for i = 1, 10 do
                if char.quests.tracked[i] ~= nil then
                    local label = row:GetNamedChild("Quest" .. i .. "Label")
                    local done = row:GetNamedChild("Quest" .. i .. "Done")
                    label:SetText(char.quests.tracked[i].name)
                    label:SetHandler('OnMouseUp', function(control, button, upInside)
                        if upInside == true and button == MOUSE_BUTTON_INDEX_RIGHT then
                            LeoAltholic.log(zo_strformat(GetString(LEOALT_REMOVED_FROM), label:GetText(), char.bio.name))
                            table.remove(LeoAltholic.savedVariables.CharList[char.bio.name].quests.tracked, i)
                            control:SetHidden(true)
                            control:GetParent():GetNamedChild("Quest" .. i .. "Done"):SetHidden(true)
                        end
                    end)
                    if char.quests.tracked[i].lastDone ~= nil then
                        if char.quests.tracked[i].lastDone <= LeoAltholic.TodayReset() then
                            done:SetText("|cCB110Enot done today|r")
                        else
                            local diff = GetTimeStamp() - char.quests.tracked[i].lastDone
                            if diff < 3600 then
                                done:SetText(zo_strformat(GetString(LEOALT_MINUTES_AGO),  math.floor(diff / 60)))
                            elseif diff < 86400 then
                                done:SetText(zo_strformat(GetString(LEOALT_HOURS_AGO),  math.floor(diff / 3600)))
                            else
                                done:SetText(zo_strformat(GetString(LEOALT_DAYS_AGO),  math.floor(diff / 86400)))
                            end
                        end
                    else
                        done:SetText("|cCB110E"..GetString(LEOALT_NOT_DONE_TODAY).."|r")
                    end
                end
            end
        end

        row = WINDOW_MANAGER:GetControlByName('LeoAltholicInventoryRow'..x)
        local color = '|c21A121'
        if char.inventory.free <= 25 then color = '|c596cfd' end
        if char.inventory.free <= 10 then color = '|cCB110E' end
        control = row:GetNamedChild("Bag")
        control:SetText(color .. char.inventory.used .. "|r / " .. char.inventory.size)
        control = row:GetNamedChild("SoulGems")
        control:SetText("|c21A121" .. char.inventory.soulGemFilled .. '|r / ' .. char.inventory.soulGemEmpty)
        control = row:GetNamedChild("Gold")
        control:SetText(formatNumber(char.inventory.gold))
        control = row:GetNamedChild("AP")
        control:SetText(formatNumber(char.inventory.ap))
        control = row:GetNamedChild("TelVar")
        control:SetText(formatNumber(char.inventory.telvar))
        control = row:GetNamedChild("Writ")
        control:SetText(formatNumber(char.inventory.writVoucher))

        row = WINDOW_MANAGER:GetControlByName('LeoAltholicResearchRow'..x)
        for _,craft in pairs(LeoAltholic.craftResearch) do
            local i = 1
            local researching = 0
            for line = 1, GetNumSmithingResearchLines(craft) do
                local lineName, lineIcon = GetSmithingResearchLineInfo(craft, line)
                for trait = 1, LeoAltholic.maxTraits do
                    local traitType = GetSmithingResearchLineTraitInfo(craft, line, trait)
                    local traitName = GetString('SI_ITEMTRAITTYPE',traitType)
                    local traitData = char.research[craft][line][trait]
                    if type(traitData) == 'number' then
                        control = row:GetNamedChild("Craft"..craft.."Label"..i)
                        control:SetText(' |t28:28:'..lineIcon..'|t  ' .. traitName)
                        control:SetHandler('OnMouseEnter', function(self) ZO_Tooltips_ShowTextTooltip(self, TOP, lineName) end)
                        control:SetHandler("OnMouseExit", function () ZO_Tooltips_HideTextTooltip() end)
                        control = row:GetNamedChild("Craft"..craft.."Timer"..i)
                        control:SetText(LeoAltholic.GetTime(traitData - GetTimeStamp()))
                        if traitData - GetTimeStamp() <= 3600 then
                            control:SetColor(1, 1, 0, 1)
                        else
                            control:SetColor(1, 1, 1, 1)
                        end
                        i = i + 1
                        if traitData - GetTimeStamp() > 0 then
                            researching = researching + 1
                        end
                    end
                end
            end
            control = row:GetNamedChild("Craft"..craft)
            color = '|c21A121'
            if researching < char.research[craft].max then
                color = '|cCB110E'
            end
            control:SetText(color .. researching .. '/' .. char.research[craft].max .. '|r')
        end

    end
end

function LeoAltholic:OnUpdate()
    if LeoAltholic:isHidden() then
        return
    end

    local control
    for x,char in pairs(LeoAltholic.GetCharacters()) do

        local riding = '|t20:20:esoui/art/mounts/ridingskill_speed.dds|t ' .. char.attributes.riding.speed .. '%' ..
                ' |t20:20:esoui/art/mounts/ridingskill_stamina.dds|t ' .. char.attributes.riding.stamina ..
                ' |t20:20:esoui/art/mounts/ridingskill_capacity.dds|t ' .. char.attributes.riding.capacity ..
                ' |t22:22:esoui/art/miscellaneous/timer_32.dds|t ' .. LeoAltholic.GetTime(char.attributes.riding.time - GetTimeStamp())
        local row = WINDOW_MANAGER:GetControlByName('LeoAltholicBioRow'..x)
        control = row:GetNamedChild('Riding')
        control:SetText(riding)

        row = WINDOW_MANAGER:GetControlByName('LeoAltholicResearchRow'..x)
        for _,craft in pairs(LeoAltholic.craftResearch) do
            local i = 1
            for line = 1, GetNumSmithingResearchLines(craft) do
                for trait = 1, LeoAltholic.maxTraits do
                    local traitData = char.research[craft][line][trait]
                    if type(traitData) == 'number' then
                        control = row:GetNamedChild("Craft"..craft.."Timer"..i)
                        control:SetText(LeoAltholic.GetTime(traitData - GetTimeStamp()))
                        if traitData - GetTimeStamp() <= 3600 then
                            control:SetColor(1, 1, 0, 1)
                        else
                            control:SetColor(1, 1, 1, 1)
                        end
                        i = i + 1
                    end
                end
            end
        end
    end
end