-- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
-- If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.

-- This is a heavily moodified fork of original work MapMate
-- Credits to its author: https://www.curseforge.com/members/devetik/projects

-- Additional fixes and added featuresa by Portalz 
-- discord: portallz

local GuildMapUI = {}
GuildMap=GuildMap
_G["GuildMapUI"] = GuildMapUI
local AceGUI = LibStub("AceGUI-3.0")
local LibKrowiWorldMapButtons = LibStub("Krowi_WorldMapButtons-1.4")
if not GuildMapDB then
    GuildMapDB = {}
end
mapButton=nil

toggleIconsCB=nil


-- Paramètres par défaut
local defaults = {
    showRanks = false,
    healthAlerts=1,
    healthAlertThreshold = 15,
    raceFilter=false,
    stealth=false,
    toggleIcons=true,
    toggleMMIcons=true,
    iconSize = 1.0,
    mmiconSize=1.0,
    lockIcon = false,
    displayLevel = true,
    simpleDots = true,
    displayName = false,
    displayHealth = false,
    ignorePlayerOnOtherLayers = false,
    showPlayersLayer = false,
    showPlayersLayerTooltip = true,
    minimap = { x = 0, y = 0, hide = false },
    GMMW = {},
    crossBroadCast=false,
    crossMyGuild="Guild Channel",
    crossMyPassword="Password"
}

-- Variable pour la fenêtre de configuration
local minimapButton -- Variable globale pour le bouton minimap

-- Fonction pour initialiser les paramètres sauvegardés
local function InitializeSettings()
    addDefaults(defaults)
    for key, value in pairs(defaults) do
        if GuildMapDB[key] == nil then
            GuildMapDB[key] = value
        end
    end
    GuildMapDB.stealth=false
    checkChannels()
end

-- Fonction pour mettre à jour le statut de verrouillage de l'icône
local function UpdateMinimapButtonLock()
    if minimapButton then
        minimapButton:SetMovable(not GuildMapDB.lockIcon)
    end
end

-- Création manuelle d'un bouton sur la minimap
local function CreateMinimapButton()
    minimapButton = CreateFrame("Button", "GuildMapMinimapButton", Minimap, "MyCircularButtonTemplate")
    minimapButton:SetFrameStrata("MEDIUM")
    minimapButton:SetFrameLevel(8)

    minimapButton:SetScript("OnClick", function(_, button)
        if button == "LeftButton" then
            GuildMapUI:ToggleConfigWindow()
        elseif button == "RightButton" then
            GuildMapUI:ToggleConfigWindow()
        end
    end)

    minimapButton:RegisterForDrag("LeftButton")
    minimapButton:SetScript("OnDragStart", function(self)
        if not GuildMapDB.lockIcon then
            self:StartMoving()
        end
    end)
    minimapButton:SetScript("OnDragStop", function(self)
        self:StopMovingOrSizing()
        local x, y = self:GetCenter()
        local mx, my = Minimap:GetCenter()
        GuildMapDB.minimap.x = x - mx
        GuildMapDB.minimap.y = y - my
    end)

    minimapButton:SetPoint("BOTTOMLEFT", Minimap, "BOTTOMLEFT", -5, -5)

    if GuildMapDB.minimap.hide then
        minimapButton:Hide()
    else
        minimapButton:Show()
    end

    minimapButton:SetScript("OnEnter", function(self)
        GameTooltip:SetOwner(self, "ANCHOR_LEFT")
        GameTooltip:SetText("GuildMap", 1, 1, 1)
        GameTooltip:AddLine(GuildMap_Localize("Left Click"), 1, 1, 1)
        GameTooltip:Show()
    end)
    minimapButton:SetScript("OnLeave", function()
        GameTooltip:Hide()
    end)

    -- Appliquer le statut initial de verrouillage
    UpdateMinimapButtonLock()
end

-- Gestion de l'ouverture et fermeture de la fenêtre
function GuildMapUI:ToggleConfigWindow()
    if configFrameProcessed and configFrameProcessed:IsShown() then
        configFrameProcessed:Hide()
    else
        configFrameProcessed=GuildMapTabOptions()
    end
end

-- Affichage de la fenêtre de paramètres
function GuildMapUI:ShowConfigWindow(container,stealthOption)
    local configFrame=container
    -- configFrame = AceGUI:Create("Frame")
    
    -- configFrame:SetCallback("OnClose", function(widget)
    --     AceGUI:Release(widget)
    --     configFrame = nil
    -- end)
    configFrame:SetLayout("Flow")
    if isStealth() then
        local stealthCheckbox = AceGUI:Create("CheckBox")
        stealthCheckbox:SetLabel(GuildMap_Localize("Stealth"))
        stealthCheckbox:SetValue(GuildMapDB.stealth)
        stealthCheckbox:SetCallback("OnValueChanged", function(_, _, value)
            GuildMapDB.stealth = value
            sendPositionWrap(true)
        end)
        configFrame:AddChild(stealthCheckbox)

            -- Create the second heading widget
        local heading0 = AceGUI:Create("Heading")
        heading0:SetText("")
        heading0:SetFullWidth(true)  -- This will also stretch across the frame
        configFrame:AddChild(heading0)
    end

    toggleIconsCB = AceGUI:Create("CheckBox")
    toggleIconsCB:SetLabel(GuildMap_Localize("Show All Icons"))
    toggleIconsCB:SetValue(GuildMapDB.toggleIcons)
    toggleIconsCB:SetCallback("OnValueChanged", function(_, _, value)
        GuildMapDB.toggleIcons = value
        mapButton:Refresh()
        if value==false then
            GuildMap:ClearAllWaypoints()
        end
        toggleMMIconsCB:SetDisabled(not value)
    end)
    configFrame:AddChild(toggleIconsCB)

    toggleMMIconsCB = AceGUI:Create("CheckBox")
    toggleMMIconsCB:SetLabel(GuildMap_Localize("Show MiniMap Icons"))
    toggleMMIconsCB:SetValue(GuildMapDB.toggleMMIcons)
    toggleMMIconsCB:SetDisabled(not GuildMapDB.toggleIcons)
    toggleMMIconsCB:SetCallback("OnValueChanged", function(_, _, value)
        GuildMapDB.toggleMMIcons = value
        if value==false then
            GuildMap:ClearAllWaypoints()
        end
    end)
    configFrame:AddChild(toggleMMIconsCB)

    
    -- local raceFilterCheckbox = AceGUI:Create("CheckBox")
    -- raceFilterCheckbox:SetLabel(GuildMap_Localize(UnitRace("player").."s Only"))
    -- raceFilterCheckbox:SetValue(GuildMapDB.showRanks)
    -- raceFilterCheckbox:SetCallback("OnValueChanged", function(_, _, value)
    --     GuildMapDB.raceFilter = value
    --     if value==true then
    --         GuildMap:ClearAllWaypoints()
    --     end
    -- end)
    -- configFrame:AddChild(raceFilterCheckbox)

    local showRanksCheckbox = AceGUI:Create("CheckBox")
    showRanksCheckbox:SetLabel(GuildMap_Localize("Show Rank"))
    showRanksCheckbox:SetValue(GuildMapDB.showRanks)
    showRanksCheckbox:SetCallback("OnValueChanged", function(_, _, value)
        GuildMapDB.showRanks = value
        guild_map_redraw_curr_pins()
    end)
    configFrame:AddChild(showRanksCheckbox)

    local simpleDots = AceGUI:Create("CheckBox")
    simpleDots:SetLabel(GuildMap_Localize("Simple Dots"))
    simpleDots:SetValue(GuildMapDB.simpleDots)
    simpleDots:SetCallback("OnValueChanged", function(_, _, value)
        GuildMapDB.simpleDots = value
        guild_map_redraw_curr_pins()
    end)
    configFrame:AddChild(simpleDots)

    -- Display Level checkbox
    local displayLevel = AceGUI:Create("CheckBox")
    displayLevel:SetLabel(GuildMap_Localize("Show Level"))
    displayLevel:SetValue(GuildMapDB.displayLevel)
    displayLevel:SetCallback("OnValueChanged", function(_, _, value)
        GuildMapDB.displayLevel = value
        guild_map_redraw_curr_pins()
    end)
    configFrame:AddChild(displayLevel)
    
    -- Display Name checkbox
    local displayName = AceGUI:Create("CheckBox")
    displayName:SetLabel(GuildMap_Localize("displayName"))
    displayName:SetValue(GuildMapDB.displayName)
    displayName:SetCallback("OnValueChanged", function(_, _, value)
        GuildMapDB.displayName = value
        guild_map_redraw_curr_pins()
    end)
    configFrame:AddChild(displayName)
        
    -- Display Health checkbox
    local displayHealth = AceGUI:Create("CheckBox")
    displayHealth:SetLabel(GuildMap_Localize("displayHealth"))
    displayHealth:SetValue(GuildMapDB.displayHealth)
    displayHealth:SetCallback("OnValueChanged", function(_, _, value)
        GuildMapDB.displayHealth = value
        guild_map_redraw_curr_pins()
    end)
    configFrame:AddChild(displayHealth)

    local lockButton = AceGUI:Create("CheckBox")
    lockButton:SetLabel(GuildMap_Localize("Icon Lock"))
    lockButton:SetValue(GuildMapDB.lockIcon)
    lockButton:SetCallback("OnValueChanged", function(_, _, value)
        GuildMapDB.lockIcon = value
        UpdateMinimapButtonLock() -- Met à jour le statut de verrouillage
    end)
    configFrame:AddChild(lockButton)

    local healthAlertsDropDown = AceGUI:Create("Dropdown")
    healthAlertsDropDown:SetLabel("Low Health Alerts")
    healthAlertsDropDown:SetList({
        [1] = "Disabled",
        [2] = "Chat Message",
        [3] = "Raid Warning (No Sound)"
    })
    healthAlertsDropDown:SetValue(GuildMapDB.healthAlerts)
    healthAlertsDropDown:SetCallback("OnValueChanged", function(_, _, value)
        GuildMapDB.healthAlerts = value
        guild_map_redraw_curr_pins()
    end)
    configFrame:AddChild(healthAlertsDropDown)

    local iconSizeSlider = AceGUI:Create("Slider")
    iconSizeSlider:SetLabel(GuildMap_Localize("Map Icon Size"))
    iconSizeSlider:SetSliderValues(25, 200, 1)
    iconSizeSlider:SetValue(GuildMapDB.iconSize * 100)
    iconSizeSlider:SetCallback("OnValueChanged", function(_, _, value)
        GuildMapDB.iconSize = value / 100
        guild_map_redraw_curr_pins()
    end)
    configFrame:AddChild(iconSizeSlider)

    local healthAlertThresholdSlider = AceGUI:Create("Slider")
    healthAlertThresholdSlider:SetLabel("Health % Alert Threshold")
    healthAlertThresholdSlider:SetSliderValues(1, 100, 1)
    healthAlertThresholdSlider:SetValue(GuildMapDB.healthAlertThreshold)
    healthAlertThresholdSlider:SetCallback("OnValueChanged", function(_, _, value)
        GuildMapDB.healthAlertThreshold = value
    end)
    configFrame:AddChild(healthAlertThresholdSlider)

    local mmiconSizeSlider = AceGUI:Create("Slider")
    mmiconSizeSlider:SetLabel(GuildMap_Localize("Minimap Icon Size"))
    mmiconSizeSlider:SetSliderValues(25, 200, 1)
    mmiconSizeSlider:SetValue(GuildMapDB.mmiconSize * 100)
    mmiconSizeSlider:SetCallback("OnValueChanged", function(_, _, value)
        GuildMapDB.mmiconSize = value / 100
        guild_map_redraw_curr_pins()
    end)
    configFrame:AddChild(mmiconSizeSlider)

    -- Ajout d'un séparateur pour les layers
    local titleHeading = AceGUI:Create("Heading")
    if titleHeading then
        titleHeading:SetText(GuildMap_Localize("Layers Settings"))
        titleHeading:SetFullWidth(true) -- Le titre occupe toute la largeur
        configFrame:AddChild(titleHeading)
    end

    --Message d'avertissement
    local yellowText = AceGUI:Create("Label")
    if yellowText then
        yellowText:SetText(GuildMap_Localize("NWB_Warning"))
        yellowText:SetFullWidth(true) -- S'étend sur toute la largeur du conteneur
        yellowText:SetColor(1, 1, 0) -- Définit la couleur en jaune (RVB : Rouge, Vert, Bleu)
        configFrame:AddChild(yellowText)
    end
    

    local ignorePlayerOnOtherLayers = AceGUI:Create("CheckBox")
    ignorePlayerOnOtherLayers:SetLabel(GuildMap_Localize("ignorePlayerOnOtherLayers"))
    ignorePlayerOnOtherLayers:SetValue(GuildMapDB.ignorePlayerOnOtherLayers)
    ignorePlayerOnOtherLayers:SetFullWidth(true)
    ignorePlayerOnOtherLayers:SetCallback("OnValueChanged", function(_, _, value)
        GuildMapDB.ignorePlayerOnOtherLayers = value
        guild_map_redraw_curr_pins()
    end)
    configFrame:AddChild(ignorePlayerOnOtherLayers)

    local showPlayersLayer = AceGUI:Create("CheckBox")
    showPlayersLayer:SetLabel(GuildMap_Localize("showPlayersLayer"))
    showPlayersLayer:SetValue(GuildMapDB.showPlayersLayer)
    showPlayersLayer:SetFullWidth(true)
    showPlayersLayer:SetCallback("OnValueChanged", function(_, _, value)
        GuildMapDB.showPlayersLayer = value
        guild_map_redraw_curr_pins()
    end)
    configFrame:AddChild(showPlayersLayer)

    local showPlayersLayerTooltip = AceGUI:Create("CheckBox")
    showPlayersLayerTooltip:SetLabel(GuildMap_Localize("showPlayersLayerTooltip"))
    showPlayersLayerTooltip:SetValue(GuildMapDB.showPlayersLayerTooltip)
    showPlayersLayerTooltip:SetFullWidth(true)
    showPlayersLayerTooltip:SetCallback("OnValueChanged", function(_, _, value)
        GuildMapDB.showPlayersLayerTooltip = value
        guild_map_redraw_curr_pins()
    end)
    configFrame:AddChild(showPlayersLayerTooltip)

    -- Create the second heading widget
    local heading2 = AceGUI:Create("Heading")
    heading2:SetText("Guide")
    heading2:SetFullWidth(true)  -- This will also stretch across the frame
    configFrame:AddChild(heading2)

    local guideText = AceGUI:Create("Label")
    guideText:SetText("/gm or /guildmap\n/gm version\n/gm count\n\nRight Click on Map Icons to invite or whisper \nOnly Rogues and Druids have the stealth option\nWait a few seconds after enabling map icons")
    guideText:SetFullWidth(true) -- S'étend sur toute la largeur du conteneur
    guideText:SetColor(.5, .5, .5) -- Définit la couleur en jaune (RVB : Rouge, Vert, Bleu)
    configFrame:AddChild(guideText)
end


function ToggleTexture(button)
    local texture = button.Icon  -- Get the texture from the button (using the parentKey defined in XML)
    if not GuildMapDB.toggleIcons then
        -- Change to a new texture
        texture:SetTexture("Interface\\AddOns\\"..guild_map_folder_name.."\\Textures\\icon.tga")
        GuildMapDB.toggleIcons = true
    else
        -- Revert back to the original texture
        texture:SetTexture("Interface\\AddOns\\"..guild_map_folder_name.."\\Textures\\iconOff.tga")
        GuildMapDB.toggleIcons = false
        GuildMap:ClearAllWaypoints()
    end
    if toggleMMIconsCB then
        toggleMMIconsCB:SetDisabled(not GuildMapDB.toggleIcons)
    end
    if toggleIconsCB then
        toggleIconsCB:SetValue(GuildMapDB.toggleIcons)
    end
end

local function IniMapButton() 
   -- Example of creating a new button using the Krowi_WorldMapButtons library

    local templateName = "MyCircularButtonTemplate"  -- The template for the button's appearance (adjust as needed)
    local templateType = "Button"         -- The type of frame, in this case, a Button

    -- Call the Add function to create the button
    mapButton = LibKrowiWorldMapButtons:Add(templateName, templateType)

    function mapButton:Refresh()
        if GuildMapDB.toggleIcons then
            -- Change to a new texture
            self.Icon:SetTexture("Interface\\AddOns\\"..guild_map_folder_name.."\\Textures\\icon.tga")
        else
            -- Revert back to the original texture
            self.Icon:SetTexture("Interface\\AddOns\\"..guild_map_folder_name.."\\Textures\\iconOff.tga")
        end
        -- Add any additional logic here, for example, updating visuals or properties
    end
    mapButton:HookScript("OnClick", function(self)
        ToggleTexture(mapButton)
    end)
    

    mapButton:SetScript("OnEnter", function(self)
        GameTooltip:SetOwner(self, "ANCHOR_RIGHT") -- Attach the tooltip to the button
        GameTooltip:SetText("Map Button Tooltip") -- Set the main text of the tooltip
        GameTooltip:AddLine("Toggle ALL Icons", 1, 1, 1) -- Add additional info (optional)
        GameTooltip:Show() -- Show the tooltip
    end)
    
    mapButton:SetScript("OnLeave", function(self)
        GameTooltip:Hide() -- Hide the tooltip when the mouse leaves the button
    end)

end

-- Fonction d'initialisation
function GuildMapUI:Initialize()
    InitializeSettings()
    CreateMinimapButton()
    IniMapButton()
    -- Initialisation au chargement de l'addon
    GuildRoster()
    local _, classFileName = UnitClass("player")
    local class = classFileName
    if not (class=="ROGUE" or class=="DRUID") then
        GuildMapDB.stealth=false
    end
    -- if DBM and DBM.HudMap then
    --     DBM.HudMap:SetFixedZoom(100)
    -- end
end

local frm = CreateFrame("Frame")
frm:RegisterEvent("PLAYER_LOGIN")
frm:SetScript("OnEvent", function(self, event)
    if event == "PLAYER_LOGIN" then
        GuildMap:RefreshPins()
    end
end)

-- Gestionnaire d'événements
local frame = CreateFrame("Frame")
frame:RegisterEvent("ADDON_LOADED")
frame:SetScript("OnEvent", function(_, _, addonName)
    if addonName == guild_map_folder_name then
        -- if event == "PLAYER_LOGIN" then
        GuildMapUI:Initialize()
        C_Timer.After(3, function()
            local scrollContainer = WorldMapFrame.ScrollContainer
            scrollContainer:HookScript("OnMouseDown", function(self, button)
                if button == "LeftButton" then
                    C_Timer.After(.5, function()
                        -- Perform the delayed action
                        GuildMap:RefreshPins()
                    end)
                    -- Perform actions for left click
                elseif button == "RightButton" then
                    C_Timer.After(.5, function()
                        -- Perform the delayed action
                        GuildMap:RefreshPins()
                    end)
                    -- Perform actions for right click
                end
            end)
            -- WorldMapFrame:HookScript("OnMouseDown", function(self, button)
            --     print(button)
                
            -- end)

            WorldMapFrame:HookScript("OnShow", function(self)
                C_Timer.After(.5, function()
                    -- Perform the delayed action
                    GuildMap:RefreshPins()
                end)
            end)

        end)
    end
end)



-- Ajout de la commande /guildmap pour ouvrir la fenêtre de configuration
SLASH_GUILDMAP1 = "/guildmap"
SLASH_GUILDMAP2 = "/gm"
SlashCmdList[guild_map_folder_name:upper()] = function(x)
    if x=="" then
        GuildMapUI:ToggleConfigWindow()
    else
        if x=="version" then
            print("|cff".."FF6600".."GuildMap Version: "..guild_map_version.."|r")
        elseif x=="count" then
            
            print("|cff".."FF6600".."Players on Map: "..tostring(GuildMap:getCount()).."|r")
        elseif x=="db" then
            -- local width = configFrame.frame:GetWidth()
            -- local height = configFrame.frame:GetHeight()
            -- guild_map_redraw_curr_pins()
            -- print("Width: " .. tostring(width))
            -- print("Height: " .. tostring(height))
            -- GuildMap:countWorldPins()
            -- lastHideTime=0
        elseif x=="dbb" then
            -- GuildMap:RefreshPins()
            -- lastHideTime=0
            guild_map_redraw_curr_pins()
        elseif x=="dbbb" then
            -- GuildMap:RefreshPins()
            -- lastHideTime=0
            guild_map_redraw_curr_pins()
        end
    end
end
