-- =========================
-- SAVED VARIABLES
-- =========================

ClearChatDB = ClearChatDB or {}

ClearChatDB.lines = ClearChatDB.lines or {
    "Chat Cleared!"
}

ClearChatDB.color = ClearChatDB.color or {
    r = 1,
    g = 1,
    b = 1
}
ClearChatDB.fontSize = ClearChatDB.fontSize or 16

-- =========================
-- CHAT CLEAR FUNCTION
-- =========================

local function ClearAllChat()

    for i = 1, NUM_CHAT_WINDOWS do

        local frame = _G["ChatFrame" .. i]

        if frame then
            frame:Clear()
        end
    end
end

-- =========================
-- CONFIG WINDOW
-- =========================

local config = CreateFrame(
    "Frame",
    "ClearChatConfigFrame",
    UIParent,
    "BasicFrameTemplateWithInset"
)
config:SetFrameStrata("TOOLTIP")
config:SetToplevel(true)

config:SetSize(360, 330)
config:SetPoint("CENTER")
config:SetMovable(true)
config:EnableMouse(true)
config:RegisterForDrag("LeftButton")

config:SetScript("OnDragStart", function(self)
    self:StartMoving()
end)

config:SetScript("OnMouseDown", function(self)
    self:Raise()
end)

config:SetScript("OnDragStop", function(self)
    self:StopMovingOrSizing()
end)

config:Hide()

config.TitleText:SetText("ClearChat")
config.TitleText:SetTextColor(1, 0.45, 0)

-- =========================
-- MESSAGE EDIT BOX
-- =========================

local label = config:CreateFontString(
    nil,
    "OVERLAY",
    "GameFontNormal"
)

label:SetPoint("TOPLEFT", 20, -45)
label:SetText("Popup Message")

local editBox = CreateFrame(
    "EditBox",
    nil,
    config,
    "InputBoxTemplate"
)

editBox:SetMultiLine(true)
editBox:SetSize(280, 100)
editBox:SetPoint(
    "TOPLEFT",
    label,
    "BOTTOMLEFT",
    0,
    -10
)

editBox:SetAutoFocus(false)

-- =========================
-- COLOR PICKER
-- =========================

local colorLabel = config:CreateFontString(
    nil,
    "OVERLAY",
    "GameFontNormal"
)

colorLabel:SetPoint(
    "TOPLEFT",
    editBox,
    "BOTTOMLEFT",
    0,
    -20
)

colorLabel:SetText("Popup Text Color")

local colorButton = CreateFrame(
    "Button",
    nil,
    config,
    "UIPanelButtonTemplate"
)

colorButton:SetSize(120, 24)

colorButton:SetPoint(
    "TOPLEFT",
    colorLabel,
    "BOTTOMLEFT",
    0,
    -10
)

colorButton:SetText("Pick Color")

local swatch = config:CreateTexture(
    nil,
    "OVERLAY"
)

swatch:SetSize(18, 18)

swatch:SetPoint(
    "LEFT",
    colorButton,
    "RIGHT",
    10,
    0
)

local function UpdateSwatch()

    local c = ClearChatDB.color

    swatch:SetColorTexture(
        c.r,
        c.g,
        c.b,
        1
    )
end

local function OpenRetailColorPicker()

    local currentColor = CopyTable(
        ClearChatDB.color
    )

    local info = {}

    info.swatchFunc = function()

        local r, g, b =
            ColorPickerFrame:GetColorRGB()

        ClearChatDB.color.r = r
        ClearChatDB.color.g = g
        ClearChatDB.color.b = b

        UpdateSwatch()
    end

    info.cancelFunc = function()

        ClearChatDB.color = currentColor

        UpdateSwatch()
    end

    info.r = currentColor.r
    info.g = currentColor.g
    info.b = currentColor.b

    info.opacity = 1
    info.hasOpacity = false

    ColorPickerFrame:SetupColorPickerAndShow(
        info
    )
end

colorButton:SetScript(
    "OnClick",
    OpenRetailColorPicker
)
-- =========================
-- FONT SIZE SLIDER
-- =========================

local fontLabel = config:CreateFontString(
    nil,
    "OVERLAY",
    "GameFontNormal"
)

fontLabel:SetPoint(
    "TOPLEFT",
    colorButton,
    "BOTTOMLEFT",
    0,
    -35
)

fontLabel:SetText(
    "Font Size: " ..
    (ClearChatDB.fontSize or 16)
)

local fontSlider = CreateFrame(
    "Slider",
    "ClearChatFontSlider",
    config,
    "OptionsSliderTemplate"
)

fontSlider:SetWidth(220)

fontSlider:SetPoint(
    "TOPLEFT",
    fontLabel,
    "BOTTOMLEFT",
    0,
    -10
)

fontSlider:SetMinMaxValues(10, 40)
fontSlider:SetValueStep(1)
fontSlider:SetObeyStepOnDrag(true)

_G[fontSlider:GetName() .. "Low"]:SetText("10")
_G[fontSlider:GetName() .. "High"]:SetText("40")
_G[fontSlider:GetName() .. "Text"]:SetText("")

fontSlider:SetScript(
    "OnValueChanged",
    function(self, value)

        value = math.floor(value)

        ClearChatDB.fontSize = value

        fontLabel:SetText(
            "Font Size: " .. value
        )
    end
)

-- =========================
-- CHANGELOG BUTTON
-- =========================

local changelogButton = CreateFrame(
    "Button",
    nil,
    config,
    "UIPanelButtonTemplate"
)

changelogButton:SetSize(100, 24)

changelogButton:SetPoint(
    "BOTTOMLEFT",
    15,
    10
)

changelogButton:SetText(
    "Changelog"
)

changelogButton:SetScript(
    "OnClick",
    function()

        if ClearChat_ShowChangelog then
            ClearChat_ShowChangelog()
        end

    end
)

-- =========================
-- SAVE BUTTON
-- =========================

local saveButton = CreateFrame(
    "Button",
    nil,
    config,
    "UIPanelButtonTemplate"
)

saveButton:SetSize(100, 24)
saveButton:SetPoint(
    "BOTTOM",
    -15,
    10
)

saveButton:SetText("Save")

saveButton:SetScript(
    "OnClick",
    function()

        local text = editBox:GetText()

        ClearChatDB.lines = {}

        for line in string.gmatch(
            text,
            "[^\n]+"
        ) do
            table.insert(
                ClearChatDB.lines,
                line
            )
        end

        if #ClearChatDB.lines == 0 then

            ClearChatDB.lines = {
                "Chat Cleared!"
            }
        end

        config:Hide()
    end
)

local function ShowConfig()

    config:Show()

    editBox:SetText(
        table.concat(
            ClearChatDB.lines,
            "\n"
        )
    )

    UpdateSwatch()

    fontSlider:SetValue(
        ClearChatDB.fontSize or 16
    )

    fontLabel:SetText(
        "Font Size: " ..
        (ClearChatDB.fontSize or 16)
    )
end

-- =========================
-- POPUP
-- =========================

local popup = CreateFrame(
    "Frame",
    "ClearChatPopup",
    UIParent,
    "BasicFrameTemplateWithInset"
)
popup:SetFrameStrata("TOOLTIP")
popup:SetToplevel(true)

popup:SetSize(280, 140)
popup:SetPoint("CENTER")

popup:SetMovable(true)
popup:EnableMouse(true)
popup:RegisterForDrag("LeftButton")

popup:SetScript("OnDragStart", function(self)
    self:StartMoving()
end)

popup:SetScript("OnDragStop", function(self)
    self:StopMovingOrSizing()
end)

popup:SetScript("OnMouseDown", function(self)
    self:Raise()
end)

popup:Hide()

popup.TitleText:SetText("ClearChat")
popup.TitleText:ClearAllPoints()

popup.TitleText:SetPoint(
    "TOP",
    popup,
    "TOP",
    10,
    -6
)


popup.text = popup:CreateFontString(
    nil,
    "OVERLAY",
    "GameFontNormalLarge"
)

popup.text:SetPoint("CENTER")
popup.text:SetWidth(220)

local closeBtn = CreateFrame(
    "Button",
    nil,
    popup,
    "UIPanelButtonTemplate"
)

closeBtn:SetSize(80, 22)
closeBtn:SetPoint(
    "BOTTOM",
    0,
    10
)

closeBtn:SetText("Close")

closeBtn:SetScript(
    "OnClick",
    function()
        popup:Hide()
    end
)


-- =========================
-- SETTINGS BUTTON
-- =========================
local settingsButton = CreateFrame(
    "Button",
    nil,
    popup
)

settingsButton:SetSize(16,16)

settingsButton:SetPoint(
    "TOPRIGHT",
    -28,
    -6
)

local settingsTexture =
    settingsButton:CreateTexture()

settingsTexture:SetAllPoints()

settingsTexture:SetTexture(
    "Interface\\Buttons\\UI-OptionsButton"
)

settingsButton:SetScript(
    "OnClick",
    function()
        popup:Hide()
        ShowConfig()
    end
)

settingsButton:SetScript(
    "OnEnter",
    function(self)
        GameTooltip:SetOwner(
            self,
            "ANCHOR_RIGHT"
        )
        GameTooltip:SetText(
            "Configuration",
            1,
            1,
            1
        )
        GameTooltip:Show()
    end
)

settingsButton:SetScript(
    "OnLeave",
    function()
        GameTooltip:Hide()
    end
)

-- =========================
-- SHOW POPUP
-- =========================

local function ShowPopup()

    local c = ClearChatDB.color

    local fontSize =
        ClearChatDB.fontSize or 16

    popup.text:SetFont(
        STANDARD_TEXT_FONT,
        fontSize,
        ""
    )

    popup.text:SetTextColor(
        c.r,
        c.g,
        c.b
    )

    popup.text:SetText(
        table.concat(
            ClearChatDB.lines,
            "\n"
        )
    )

    popup.text:SetWidth(
        math.max(
            220,
            fontSize * 12
        )
    )

    local textWidth =
        popup.text:GetStringWidth()

    local textHeight =
        popup.text:GetStringHeight()

    popup:SetSize(
        math.max(
            280,
            textWidth + 80
        ),
        math.max(
            140,
            textHeight + 90
        )
    )

    popup:Show()

    C_Timer.After(
        60,
        function()

            if popup:IsShown() then
                popup:Hide()
            end

        end
    )
end

-- =========================
-- SLASH COMMAND
-- =========================

SLASH_CLEARCHAT1 = "/clear"

SlashCmdList["CLEARCHAT"] =
function(msg)

    msg = msg and msg:lower()

    if msg == "config" then
        ShowConfig()
    else
        ClearAllChat()
        ShowPopup()
    end
end

-- =========================
-- ADDON CATEGORY
-- =========================

local ClearChatCategory = CreateFrame("Frame")

ClearChatCategory.name = "ClearChat"

InterfaceOptions_AddCategory(
    ClearChatCategory
)
config.name = "Settings"
config.parent = "ClearChat"

InterfaceOptions_AddCategory(
    config
)