LeoGM.hidden = true
LeoGM.memberScroll = nil
LeoGM.selectedRank = nil

LeoGMMemberList = ZO_SortFilterList:Subclass()
function LeoGMMemberList:New(control)

    ZO_SortFilterList.InitializeSortFilterList(self, control)

    local sorterKeys =
    {
        ["name"] = {},
        ["deposits"] = { isNumeric = true, tiebreaker = "name"},
        ["sales"] = { isNumeric = true, tiebreaker = "name"},
        ["online"] = { isNumeric = true, tiebreaker = "name"},
        ["rankIndex"] = { isNumeric = true, tiebreaker = "name"},
    }

    self.masterList = {}
    ZO_ScrollList_AddDataType(self.list, 1, "LeoGMMemberListTemplate", 32, function(control, data) self:SetupEntry(control, data) end)

    self.sortFunction = function(listEntry1, listEntry2)
        return ZO_TableOrderingFunction(listEntry1.data, listEntry2.data, self.currentSortKey, sorterKeys, self.currentSortOrder)
    end
    self:SetAlternateRowBackgrounds(true)

    return self
end

function LeoGM.UserClick(control, button, upInside)
    local player = control.data
    local guildId = LeoGM.GetGuilds(LeoGM.savedVariables.selectedGuild)
    if type(player) == 'string' and button == MOUSE_BUTTON_INDEX_RIGHT then
        ClearMenu()
        AddMenuItem(GetString(SI_SOCIAL_LIST_SEND_MESSAGE), function() StartChatInput(nil, CHAT_CHANNEL_WHISPER, player) end)
        AddMenuItem(GetString(SI_SOCIAL_MENU_SEND_MAIL), function() MAIL_SEND:ComposeMailTo(player) end)
        if DoesPlayerHaveGuildPermission(guildId, GUILD_PERMISSION_NOTE_EDIT) then
            -- Soon
            --AddMenuItem(GetString(SI_SOCIAL_MENU_EDIT_NOTE), LeoGM.EditMemberNote(control, player))
        end
        if DoesPlayerHaveGuildPermission(guildId, GUILD_PERMISSION_DEMOTE) then
            AddMenuItem(GetString(SI_GUILD_DEMOTE), function() GuildDemote(guildId, player) end)
        end
        if DoesPlayerHaveGuildPermission(guildId, GUILD_PERMISSION_REMOVE) then
            AddMenuItem(GetString(SI_GUILD_REMOVE), function() GuildRemove(guildId, player) end)
        end
        ShowMenu(control)
    end
end

function LeoGMMemberList:SetupEntry(control, data)

    control.data = data

    control.name = GetControl(control, "Name")
    control.name:SetText(data.name)
    control.name.data = data.name

    control.deposits = GetControl(control, "Deposits")
    control.deposits:SetText(LeoGM.formatNumber(data.deposits))

    control.sales = GetControl(control, "Sales")
    control.sales:SetText(LeoGM.formatNumber(data.sales))

    control.online = GetControl(control, "Online")
    control.online:SetText(LeoGM.GetTime(data.online))

    local guildId = LeoGM.GetGuilds(LeoGM.savedVariables.selectedGuild)
    local rankName = GetGuildRankCustomName(guildId, data.rankIndex)
    if rankName:len() == 0 then
        rankName = "Guildmaster"
    end
    control.rank = GetControl(control, "Rank")
    control.rank:SetText(rankName)

    ZO_SortFilterList.SetupRow(self, control, data)
end

function LeoGMMemberList:BuildMasterList()
    self.masterList = {}
    local list = LeoGM.members
    if list then
        for k, v in ipairs(list) do
            local data = v
            table.insert(self.masterList, data)
        end
    end
end

function LeoGMMemberList:SortScrollList()
    local scrollData = ZO_ScrollList_GetDataList(self.list)
    table.sort(scrollData, self.sortFunction)
end

function LeoGMMemberList:FilterScrollList()

    local scrollData = ZO_ScrollList_GetDataList(self.list)
    ZO_ClearNumericallyIndexedTable(scrollData)

    local ticketsThreshold = LeoGMWindowRulesPanelTicketsSlider:GetValue() * 1000
    local salesThreshold = LeoGMWindowRulesPanelSalesSlider:GetValue() * 1000
    local offlineThreshold = LeoGMWindowRulesPanelOfflineSlider:GetValue() * 24 * 60 * 60

    for i = 1, #self.masterList do
        local data = self.masterList[i]
        local canAdd = true
        if salesThreshold > 0 and ticketsThreshold > 0 and ( data.sales >= salesThreshold or data.deposits >= ticketsThreshold ) then
            canAdd = false
        elseif salesThreshold > 0 and data.sales >= salesThreshold then
            canAdd = false
        elseif ticketsThreshold > 0 and data.deposits >= ticketsThreshold then
            canAdd = false
        end
        if not canAdd and offlineThreshold > 0 and data.online > offlineThreshold then
            canAdd = true
        end
        if canAdd and LeoGM.selectedRank and data.rankIndex <= LeoGM.selectedRank then
            canAdd = false
        end
        if canAdd then
            table.insert(scrollData, ZO_ScrollList_CreateDataEntry(1, data))
        end
    end
    LeoGMWindowPurgePanelListResult:SetText("Total: " .. #scrollData)
end

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

function LeoGM:isHidden()
    return LeoGM.hidden
end

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

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

function LeoGM.ShowUI()
    SCENE_MANAGER:ShowTopLevel(LeoGMWindow)
    LeoGMWindow:SetHidden(false)
    LeoGM.hidden = false;
    if not LeoGM.savedVariables.activeTab then
        LeoGM.savedVariables.activeTab = "Rules"
    end
    LeoGM.ShowTab(LeoGM.savedVariables.activeTab)
end

function LeoGM.HideUI()
    SCENE_MANAGER:HideTopLevel(LeoGMWindow)
    LeoGMWindow:SetHidden(true)
    LeoGM.hidden = true;
end

function LeoGM.ToggleUI()
    if LeoGM:isHidden() then
        LeoGM.ShowUI()
    else
        LeoGM.HideUI()
    end
end

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

function LeoGMWindow.OnRangeSliderMoved(self)
    LeoGMWindowPurgePanelRangeValue:SetText(LeoGMWindow.GetRangeText())
    LeoGMWindow.OnDepositSliderMoved()
    LeoGMWindow.OnSaleSliderMoved()
end

function LeoGMWindow.GetRangeText()
    local sliderLevel = LeoGMWindowPurgePanelRangeSlider:GetValue()
    if sliderLevel == 1 then
        sliderLevel = sliderLevel .. " day"
    else
        sliderLevel = sliderLevel .. " days"
    end
    return sliderLevel
end

function LeoGMWindow.OnTicketsSliderMoved()
    local sliderLevel = LeoGMWindowRulesPanelTicketsSlider:GetValue()
    LeoGM.savedVariables.rules[LeoGM.savedVariables.selectedGuild].tickets = sliderLevel
    if sliderLevel > 0 then
        sliderLevel = sliderLevel .. "k"
    else
        sliderLevel = "disabled"
    end
    LeoGMWindowRulesPanelTicketsValue:SetText(sliderLevel)
    LeoGMWindow.UpdateRequirementsDesc()
end

function LeoGMWindow.OnSalesSliderMoved()
    local sliderLevel = LeoGMWindowRulesPanelSalesSlider:GetValue()
    LeoGM.savedVariables.rules[LeoGM.savedVariables.selectedGuild].sales = sliderLevel
    if sliderLevel > 0 then
        sliderLevel = sliderLevel .. "k"
    else
        sliderLevel = "disabled"
    end
    LeoGMWindowRulesPanelSalesValue:SetText(sliderLevel)
    LeoGMWindow.UpdateRequirementsDesc()
end

function LeoGMWindow.OnOfflineSliderMoved()
    local sliderLevel = LeoGMWindowRulesPanelOfflineSlider:GetValue()
    LeoGM.savedVariables.rules[LeoGM.savedVariables.selectedGuild].offline = sliderLevel
    if sliderLevel > 0 then
        sliderLevel = sliderLevel .. " days"
    else
        sliderLevel = "disabled"
    end
    LeoGMWindowRulesPanelOfflineValue:SetText(sliderLevel)
    LeoGMWindow.UpdateRequirementsDesc()
end

function LeoGMWindow.UpdateRequirementsDesc()
    local tickets = LeoGMWindowRulesPanelTicketsSlider:GetValue()
    local sales = LeoGMWindowRulesPanelSalesSlider:GetValue()
    local offline = LeoGMWindowRulesPanelOfflineSlider:GetValue()
    local descRule = ''
    local descPurge = 'List members'

    if tickets > 0 and sales > 0 then
        descRule = "At least " .. tickets .. "k in raffle tickets OR " .. sales .. "k sales per week"
        descPurge = descPurge .. " with less than " .. tickets .. "k in raffle tickets OR " .. sales .. "k sales last 7 days"
    elseif tickets > 0 then
        descRule = "At least " .. tickets .. "k in raffle tickets per week"
        descPurge = descPurge .. " with less than " .. tickets .. "k in raffle tickets last 7 days"
    elseif sales > 0 then
        descRule = "At least " .. sales .. "k sales per week"
        descPurge = descPurge .. " with less than " .. sales .. "k sales last 7 days"
    end

    if offline > 0 then
        if tickets > 0 or sales > 0 then descRule = descRule .. " AND " end
        descRule = descRule .. "Inactivity policy of " .. offline .. " days"
        descPurge = descPurge .. ". Inactive for more than " .. offline .. " days"
    end
    LeoGMWindowRulesPanelRequirementsDesc:SetText(descRule)
    LeoGMWindowPurgePanelPurgeDesc:SetText(descPurge)
end

function LeoGM.ListPurge()
    local guildId = LeoGM.GetGuilds(LeoGM.savedVariables.selectedGuild)

    if not DoesPlayerHaveGuildPermission(guildId, GUILD_PERMISSION_BANK_VIEW_GOLD) then
        LeoGMWindowPurgePanelListResult:SetText("|cFF2222You don't have permission to scan guild gold deposits.|r")
        return
    end
    if MasterMerchant == nil or
        MasterMerchant.guildSales[LeoGM.savedVariables.selectedGuild] == nil or
        MasterMerchant.guildSales[LeoGM.savedVariables.selectedGuild].sellers == nil
    then
        LeoGMWindowPurgePanelListResult:SetText("|cFF2222MasterMerchant sales data not found for this guild.|r Try again in a few moments if it is still initializing.")
        return
    end
    LeoGM.GetGuildMembers(guildId)
    local scanSince = GetTimeStamp() - 7 * 24 * 60 * 60
    LeoGM.BuildDepositsHistory(guildId, scanSince)
end

function LeoGM.InitializeUI()
    LeoGMWindowTitle:SetText(LeoGM.displayName .. " v" .. LeoGM.version)

    local LeoGMWindowGuildDropdown = CreateControlFromVirtual('LeoGMWindowGuildDropdown', LeoGMWindow, 'LeoGMWindowDropdown')
    LeoGMWindowGuildDropdown:SetDimensions(200,35)
    LeoGMWindowGuildDropdown:SetAnchor(LEFT, LeoGMWindowHeaderBG, RIGHT, -204, 0)
    LeoGMWindowGuildDropdown.m_comboBox:SetSortsItems(false)
    local guildDropdown = ZO_ComboBox_ObjectFromContainer(LeoGMWindowGuildDropdown)
    guildDropdown:ClearItems()

    local defaultItem
    for _, guildName in pairs(LeoGM.guilds) do
        local guildEntry = guildDropdown:CreateItemEntry(guildName, function()
            LeoGM.savedVariables.selectedGuild = guildName

            LeoGMWindowRulesPanelTicketsSlider:SetValue(LeoGM.savedVariables.rules[LeoGM.savedVariables.selectedGuild].tickets)
            LeoGMWindowRulesPanelSalesSlider:SetValue(LeoGM.savedVariables.rules[LeoGM.savedVariables.selectedGuild].sales)
            LeoGMWindowRulesPanelOfflineSlider:SetValue(LeoGM.savedVariables.rules[LeoGM.savedVariables.selectedGuild].offline)

            local guildId = LeoGM.GetGuilds(guildName)
            local rankDropdown = ZO_ComboBox_ObjectFromContainer(LeoGMWindowRankDropdown)
            rankDropdown:ClearItems()
            rankDropdown:AddItem(rankDropdown:CreateItemEntry(" "))
            for i = 1, GetNumGuildRanks(guildId) do
                local rankName = GetGuildRankCustomName(guildId, i)
                if rankName:len() == 0 then
                    rankName = "Guildmaster"
                end
                local rankEntry = rankDropdown:CreateItemEntry(rankName, function()
                    LeoGM.selectedRank = i
                    LeoGMWindow.UpdateRequirementsDesc()
                    local desc = LeoGMWindowPurgePanelPurgeDesc:GetText()
                    if rankName:len() > 0 then
                        desc = desc .. ". Ignore members with rank " .. rankName .. " or higher"
                    end
                    LeoGMWindowPurgePanelPurgeDesc:SetText(desc)
                end)
                rankDropdown:AddItem(rankEntry)
            end
        end)
        if not LeoGM.savedVariables.rules[guildName] then
            LeoGM.savedVariables.rules[guildName] = {
                tickets = 0,
                sales = 0,
                offline = 0
            }
        end
        if not LeoGM.savedVariables.selectedGuild then
            LeoGM.savedVariables.selectedGuild = guildName
        end
        if LeoGM.savedVariables.selectedGuild and LeoGM.savedVariables.selectedGuild == guildName then
            defaultItem = guildEntry
        end
        guildDropdown:AddItem(guildEntry)
    end

    local LeoGMWindowRankDropdown = CreateControlFromVirtual('LeoGMWindowRankDropdown', LeoGMWindowPurgePanel, 'LeoGMWindowDropdown')
    LeoGMWindowRankDropdown:SetDimensions(270,35)
    LeoGMWindowRankDropdown:SetAnchor(LEFT, LeoGMWindowPurgePanelRankLabel, RIGHT, 10, 0)
    LeoGMWindowRankDropdown.m_comboBox:SetSortsItems(false)

    if defaultItem ~= nil then
        guildDropdown:SelectItem(defaultItem)
    end

    if LeoGM.savedVariables.selectedGuild then
        LeoGMWindowRulesPanelTicketsSlider:SetValue(LeoGM.savedVariables.rules[LeoGM.savedVariables.selectedGuild].tickets)
        LeoGMWindowRulesPanelSalesSlider:SetValue(LeoGM.savedVariables.rules[LeoGM.savedVariables.selectedGuild].sales)
        LeoGMWindowRulesPanelOfflineSlider:SetValue(LeoGM.savedVariables.rules[LeoGM.savedVariables.selectedGuild].offline)
    end

    LeoGM.memberScroll = LeoGMMemberList:New(LeoGMWindowPurgePanelMemberScroll) -- check

    LeoGMWindowPurgePanelLoadingIcon.animation = ANIMATION_MANAGER:CreateTimelineFromVirtual('LoadIconAnimation', LeoGMWindowPurgePanelLoadingIcon)
end

function LeoGM.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) .. "d " .. tostring (hh - (dn*24)) .. "h"
        elseif hh > 0 then result = tostring (hh) .. "h " .. tostring (mm) .. "m"
        elseif mm > 0 then result = mm .. "m " .. ss .. "s"
        end
        return result
    else return 'online' end
end

ZO_CreateStringId('SI_BINDING_NAME_LEOGM_TOGGLE_WINDOW', "Show/Hide Main Window")