-- This file is a private addition by Portalz - officialportalz@gmail.com.
-- its an absolute monstrosity of a mess, but its my mess i coded quickly but carefully
-- It is not part of the GuildMap MPL 2.0 codebase.
-- All rights reserved.

-- local GuildMapUI = {}
-- _G["GuildMapTest"] = GuildMapTest

-- working on getting cross guild working but its painful

local AceGUI = LibStub("AceGUI-3.0")
GMMW= GMMW or {}
GuildMapDB=GuildMapDB or {}
GuildMapDB.GMMW=GuildMapDB.GMMW or {}
-- hooksecurefunc("UseItemByName", function(itemName)
--     SendChatMessage("Using my Healthstone!", "SAY")
-- end)

-- local castFrameCheck = CreateFrame("Frame")
-- castFrameCheck:RegisterEvent("UNIT_SPELLCAST_SUCCEEDED")
-- castFrameCheck:SetScript("OnEvent", function(self, event, unit, spellName)
--     print("EVENT TRIGGERED")
--     SendChatMessage("TEST", "CHANNEL", nil, GetChannelName(GuildMapDB.crossMyGuild))
--     -- if timeSinceLastUpdate > maxTimeBetweenUpdate then
--     --     sendPositionChat()
--     -- end
-- end)

function OnAddonMessageWrap(prefix, text, channel, sender)
    OnAddonMessage(prefix, text, channel, sender)
end

function sendPositionWrap(x)
    message=GuildMap:SendGuildPosition(x)
    if message then
        C_ChatInfo.SendAddonMessage(ADDON_PREFIX, message, "GUILD")
    end
    timeSinceLastUpdate=0
end

function sendPositionChat()
    message=GuildMap:SendGuildPosition(x)
    timeSinceLastUpdate=timeSinceLastUpdateExternal
    if message then
        C_ChatInfo.SendAddonMessage(ADDON_PREFIX, message, "GUILD")
        if GuildMapDB.crossBroadCast then
            SendChatMessage(message, "CHANNEL", nil, GetChannelName(GuildMapDB.crossMyGuild))
            timeSinceLastUpdate=0
            timeSinceLastUpdateExternal = 0
        end
    end
end

function checkChannels()
    channelStatus={}
    local channels = { GetChannelList() }
    if #channels == 0 then
        return
    end

    -- print("Connected Channels:")
    for i = 1, #channels, 3 do
        local channelNumber = channels[i]
        local channelName = channels[i + 1]
        local isPasswordProtected = channels[i + 2]
        local protectionStatus = isPasswordProtected and "Password Protected" or "No Password"
        if GuildMapDB.GMMW[channelName] then
            channelStatus[channelName]=true
            if not GuildMapDB.GMMW[channelName].setBroadcast then
                LeaveChannelByName(channelName)
            end
        end

        if GuildMapDB.crossMyGuild==channelName and not GuildMapDB.crossBroadCast then
            LeaveChannelByName(channelName)
        end
        -- print(string.format("%d: %s (%s)", channelNumber, channelName, protectionStatus))
    end

    for channeName,channel in pairs(GuildMapDB.GMMW) do
        local myGuild=false

        if not channelStatus[channeName] and  GuildMapDB.GMMW[channeName].setBroadcast then
            -- print("Attempting Connection to Connect to"..channeName)
            JoinChannelByName(channeName, channel.setEditPassword)
        end

        if channelName==GuildMapDB.crossMyGuild then
            myGuild=true
        end
    end

    if not myGuild and GuildMapDB.crossBroadCast then
        -- print("Attempting Connection to Connect to"..GuildMapDB.crossMyGuild)
        JoinChannelByName(GuildMapDB.crossMyGuild, GuildMapDB.crossMyPassword)
    end
end



function addDefaults(defaults)
    defaults.crossBroadCast=false
    defaults.crossMyGuild=nil
    defaults.crossMyPassword=nil
    defaults.otherGuilds=nil
end

function isStealth()
    local stealthOption=false
    --   if class=="DRUID" or class=="ROGUE" then
        stealthOption=true
    --   end
    return stealthOption
end
function crossGuildMyTab(container)
    local desc = AceGUI:Create("Label")
    desc:SetText("This is Tab 1")
    desc:SetFullWidth(true)
    container:AddChild(desc)
    
    local broadcastLocationOp = AceGUI:Create("CheckBox")
    broadcastLocationOp:SetLabel("Broadcast to other Guilds")
    broadcastLocationOp:SetWidth(300)
    broadcastLocationOp:SetValue(GuildMapDB.crossBroadCast)
    broadcastLocationOp:SetCallback("OnValueChanged", function(_, _, value)
        GuildMapDB.crossBroadCast = value
        broadcastLocationOp:SetValue(value)
        if not value then
            LeaveChannelByName(GuildMapDB.crossMyGuild)
        else
            JoinChannelByName(GuildMapDB.crossMyGuild, GuildMapDB.crossMyPassword)
        end
        sendPositionWrap(true)
    end)
    container:AddChild(broadcastLocationOp)
    
    -- local frame = AceGUI:Create("Frame")
    -- container.SetLayout("Flow")
    -- Add content to the frame
    local label1 = AceGUI:Create("Label")
    label1:SetText("Guild Channel")
    label1:SetWidth(350)
    container:AddChild(label1)

    local editBoxName = AceGUI:Create("EditBox")
    editBoxName:SetWidth(350)
    editBoxName:SetText(GuildMapDB.crossMyGuild or "Channel")
    prevEditBoxNameMy=GuildMapDB.crossMyGuild
    editBoxName:SetCallback("OnEnterPressed", function(_, _, value)
        if value then
            editBoxName:SetText(value:lower())
            GuildMapDB.crossMyGuild = value:lower()
            LeaveChannelByName(prevEditBoxNameMy)
            prevEditBoxNameMy=GuildMapDB.crossMyGuild
        end
        checkChannels()
    end)
    container:AddChild(editBoxName)

    local label2 = AceGUI:Create("Label")
    label2:SetText("Guild Password Case Sensitive")
    label2:SetWidth(350)
    container:AddChild(label2)

    local editBoxPassword = AceGUI:Create("EditBox")
    editBoxPassword:SetWidth(350)
    editBoxPassword:SetText(GuildMapDB.crossMyPassword or "Password")
    prevEditBoxName=GuildMapDB.crossMyPassword
    editBoxPassword:SetCallback("OnEnterPressed", function(_, _, value)
        GuildMapDB.crossMyPassword = value
        prevEditBoxName=GuildMapDB.crossMyPassword
        checkChannels()
    end)
    container:AddChild(editBoxPassword)
end

--add function to refresh channels --channels need prefix?

function crossGuildScrolLTab(container)
    local desc = AceGUI:Create("Label")
    desc:SetText("This is Tab 1")
    desc:SetFullWidth(true)
    container:AddChild(desc)


    local button = AceGUI:Create("Button")
    button:SetText("Add Guild")
    button:SetWidth(200)
    
    container:AddChild(button)

    
    local scrollFrame = AceGUI:Create("ScrollFrame")
    -- scrollFrame.SetLayout("Flow")
    scrollFrame:SetWidth(400)
    scrollFrame:SetHeight(350)
    button:SetCallback("OnClick", function(widget, event)
        --refresh tab
        container:ReleaseChildren()
        crossGuildScrolLTab(container)

        -- for key,block in pairs(GMMW) do
        --     print(key)
        --     block.setEditChannel=key
        --     print(block.setBroadcast)
        --     print(block.setEditChannel)
        --     print(block.setEditPassword)
        --     local newBlock=createCrossGuildBlock(scrollFrame,container,block)
        --     scrollFrame:AddChild(newBlock)
            
        -- end

        local newBlock=createCrossGuildBlock(scrollFrame,container)
        scrollFrame:AddChild(newBlock)
    end)

    for key,block in pairs(GuildMapDB.GMMW) do
        block.setEditChannel=key
        local newBlock=createCrossGuildBlock(scrollFrame,container,block)
        scrollFrame:AddChild(newBlock)
        
    end

    container:AddChild(scrollFrame)
end

function createCrossGuildBlock(xfr,tabContainer,settings)
    local scrollFrame = AceGUI:Create("SimpleGroup")

    if not settings then
        settings= {
            setBroadcast=false,
            setEditChannel="Guild Channel",
            setEditPassword="Password"
        }
    end
    
    local broadcastLocationOp = AceGUI:Create("CheckBox")
    broadcastLocationOp:SetLabel("Enabled")
    broadcastLocationOp:SetWidth(200)
    broadcastLocationOp:SetValue(settings.setBroadcast)
    scrollFrame:AddChild(broadcastLocationOp)
    local label1 = AceGUI:Create("Label")
    label1:SetText("Guild Channel")
    label1:SetWidth(350)
    scrollFrame:AddChild(label1)

    
    local editBoxName = AceGUI:Create("EditBox")
    editBoxName:SetText(settings.setEditChannel)
    prevEditBoxName=settings.setEditChannel
    editBoxName:SetWidth(350)
    
    scrollFrame:AddChild(editBoxName)

    local label2 = AceGUI:Create("Label")
    label2:SetText("Guild Password Case Sensitive")
    label2:SetWidth(350)
    scrollFrame:AddChild(label2)

    local editBoxPassword = AceGUI:Create("EditBox")
    editBoxPassword:SetText(settings.setEditPassword)
    prevEditPassword=settings.setEditPassword
  
    editBoxPassword:SetWidth(350)
    scrollFrame:AddChild(editBoxPassword)


    broadcastLocationOp:SetCallback("OnValueChanged", function(_, _, value)
        broadcastLocationOp:SetValue(value)
        GuildMapDB.GMMW[editBoxName:GetText()]={
            setEditPassword=editBoxPassword:GetText(),
            setBroadcast=broadcastLocationOp:GetValue()
        }
        if not value then
            LeaveChannelByName(editBoxName:GetText())
            GuildMap:ClearAllWaypoints()
        else
            JoinChannelByName(editBoxName:GetText(), editBoxPassword:GetText())
        end
    end)

    editBoxPassword:SetCallback("OnEnterPressed", function(_, _, value)
        GuildMapDB.GMMW[editBoxName:GetText()]={
            setEditPassword=editBoxPassword:GetText(),
            setBroadcast=broadcastLocationOp:GetValue()
        }
        checkChannels()
    end)

    editBoxName:SetCallback("OnEnterPressed", function(_, _, value)
        if value then
            GuildMapDB.GMMW[prevEditBoxName]=nil
            editBoxName:SetText(value:lower())
            GuildMapDB.GMMW[value:lower()]={
                setEditPassword=editBoxPassword:GetText(),
                setBroadcast=broadcastLocationOp:GetValue()
            }
            LeaveChannelByName(prevEditBoxName)
            prevEditBoxName=value:lower()
            checkChannels()
        end
        
    end)
    
    local delete = AceGUI:Create("Button")
    delete:SetText("Delete")
    delete:SetWidth(200)
    delete:SetCallback("OnClick", function(widget, event)
        -- GMMW[editBoxName:GetText()]=nil
        tabContainer:ReleaseChildren()
        GuildMapDB.GMMW[editBoxName:GetText()]=nil
        crossGuildScrolLTab(tabContainer)
        LeaveChannelByName(editBoxName:GetText())
        -- for _,block in pairs(GuildMapDB.GMMW) do
        --     block.setEditChannel=_
        --     local newBlock=createCrossGuildBlock(xfr,tabContainer,block)
        --     xfr:AddChild(newBlock)
        -- end
    end)
    scrollFrame:AddChild(delete)
    local label3 = AceGUI:Create("Label")
    label3:SetText("    ")
    label3:SetWidth(350)
    scrollFrame:AddChild(label3)

    local separator = AceGUI:Create("Heading")
    -- separator:SetText("Button " .. i)
    separator:SetWidth(350)
    scrollFrame:AddChild(separator)

    scrollFrame:SetFullWidth(true)
    scrollFrame:SetFullHeight(true)
    -- scrollFrame:SetLayout("Fill")
    -- xfr:AddChild(scrollFrame)

    return scrollFrame
    
end

function GuildMapTabOptions(configFrame)
  -- function that draws the widgets for the first tab
  local function DrawGroup1(container)
    
  end
  
  -- function that draws the widgets for the second tab
  local function DrawGroup2(container)
    GuildMapUI:ShowConfigWindow(container)
  end
  
  -- Callback function for OnGroupSelected
  local function SelectGroup(container, event, group)
     container:ReleaseChildren()
     if group == "core" then
        DrawGroup2(container,isStealth())
    elseif group == "tab2" then
        crossGuildMyTab(container)
     elseif group == "tab3" then
        crossGuildScrolLTab(container)
     end
  end
  
  -- Create the frame container
  local frame = AceGUI:Create("Frame")

--   Add the frame as a global variable under the name `MyGlobalFrameName`
    _G["GuildMapGFrameX"] = frame.frame
    -- Register the global variable `MyGlobalFrameName` as a "special frame"
    -- so that it is closed when the escape key is pressed.
    tinsert(UISpecialFrames, "GuildMapGFrameX")


    local frameHeight=565
    local _, class = UnitClass("player")
    
    if isStealth() then
        frameHeight=610
    end
 
  frame:SetWidth(495)
  frame:SetHeight(frameHeight)



  frame:SetTitle("Example Frame")
  frame:SetTitle("GuildMap Options")
  frame:SetStatusText("Discord: `portallz` for bugs")
  frame:SetCallback("OnClose", function(widget) AceGUI:Release(widget) end)
  -- Fill Layout - the TabGroup widget will fill the whole frame
  frame:SetLayout("Fill")
  
  -- Create the TabGroup
  local tab =  AceGUI:Create("TabGroup")
  tab:SetLayout("Flow")
  -- Setup which tabs to show
--   tab:SetTabs({{text="Core", value="core"}, {text="My Guild", value="tab2"},{text="Other Guilds", value="tab3"}})
  tab:SetTabs({{text="Core", value="core"},})
  -- Register callback
  tab:SetCallback("OnGroupSelected", SelectGroup)
  -- Set initial Tab (this will fire the OnGroupSelected callback)
  tab:SelectTab("core")
  
  -- add to the frame container
  frame:AddChild(tab)

  return frame

end
