--## Author: TuTu、huchang47 ## Version: 1.0.5

local TankHappy = LibStub("AceAddon-3.0"):NewAddon("TankHappy")
-- 本地化名称
local TankHappyLocal = (GetLocale() == "zhCN" or GetLocale() == "zhTW") and "|cff33ff99[便捷]|r坦克开心" or "Tank Happy"

local _, classEn = UnitClass("player")
-- 非猎人、盗贼、萨满则不加载
if not (classEn == "HUNTER" or classEn == "ROGUE" or classEn == "SHAMAN") then return end

-- 根据职业设置法术ID
local spell = classEn == "HUNTER" and 34477 or classEn == "ROGUE" and 57934 or 974

local aura_env = {
    config = {
        name = "TankHappy",
        icon = "Interface\\Icons\\Ability_Hunter_WingClip",
        desc = "自动选择误导、嫁祸、地盾坦克或者宠物",
        author = "TuTu，huchang47",
        version = "1.0.5"
    }
}
local name = aura_env.config.name
local btn = _G[name]
local InfoOutput = false

-- buff/debuff检查函数
local function UnitAura(unit, auraName)
    return AuraUtil.FindAuraByName(auraName, unit) ~= nil
end

-- 加载队伍成员专精检测库
--aura_env.inspect = LibStub:GetLibrary("LibGroupInSpecT-1.1", true)
aura_env.last = nil

-- 创建或复用按钮
if not btn then
    btn = CreateFrame("Button", name, UIParent, "SecureActionButtonTemplate")
    btn:SetSize(32, 32)
    btn:RegisterForClicks("AnyUp", "AnyDown")
    btn:SetHighlightTexture('Interface\\Buttons\\ButtonHilight-Square')
    btn:SetAttribute("type", "spell")
    btn:SetAttribute("unit", "target")
    btn:SetAttribute("spell", spell)
    btn:SetAttribute("checkselfcast", false)
    btn:SetAttribute("checkfocuscast", false)
end
aura_env.btn = btn

-- 更新宏目标的函数
aura_env.UpdateMacro = function(unit)
    local text
    local lastText = aura_env.lastText or ""
    if UnitExists(unit) then
        local spellName = C_Spell.GetSpellName(spell)
        if not spellName then
            print(aura_env.id, "错误", "未知法术 " .. spell)
        end
        if not InCombatLockdown() and not UnitAffectingCombat("player") then
            if classEn == "SHAMAN" and IsPlayerSpell(383010) then
                local hasShield = UnitAura("player", spellName)
                if not hasShield then
                    btn:SetAttribute("unit", "player")
                    text = C_Spell.GetSpellLink(spell).. " 目标为自己"
                else
                    btn:SetAttribute("unit", unit)
                    -- 增加队伍判断
                    if IsInGroup() then
                        text = C_Spell.GetSpellLink(spell).. " 已存在于自己，目标切换到坦克"
                    else
                        text = C_Spell.GetSpellLink(spell).. " 已对自己施放"
                    end
                end
            else
                btn:SetAttribute("unit", unit)
                text = C_Spell.GetSpellLink(spell) .. " 选中目标：-> " .. unit
            end
        else
            aura_env.needUpdate = true
            return
        end
    else
        if not InCombatLockdown() and not UnitAffectingCombat("player") then
            btn:SetAttribute("unit", "target")
            text = C_Spell.GetSpellLink(spell) .. " 无目标"
        end
    end
    if text and text ~= lastText then
        if InfoOutput then
            print(text)
        end
        aura_env.lastText = text
    end
end

-- 检测坦克的函数
local members = {"party1", "party2", "party3", "party4", "party1pet", "party2pet", "party3pet", "party4pet"}
aura_env.UpdateTank = function()
    if InCombatLockdown() or IsInRaid() then return end
    if UnitExists("focus") and UnitIsFriend("player", "focus") and UnitCanAssist("player", "focus") then
        aura_env.UpdateMacro("focus")
        return
    end
    for i = 1, #members do
        local unit = UnitName(members[i])
        if unit then
            if i >= 5 then
                aura_env.UpdateMacro(unit)
                return
            end
            if UnitGroupRolesAssigned(unit) == "TANK" and UnitIsConnected(unit) then
                aura_env.UpdateMacro(unit)
                return
            end
        end
    end
    if classEn == "HUNTER" then
        aura_env.UpdateMacro("pet")
    elseif classEn == "ROGUE" then
        aura_env.UpdateMacro()
    elseif classEn == "SHAMAN" then
        aura_env.UpdateMacro("player")
    end
end

function TankHappy:OnInitialize()
    if not InCombatLockdown() then C_Timer.NewTicker(1, aura_env.UpdateTank) end
    self.db = LibStub("AceDB-3.0"):New("TankHappyDB", {
        profile = {
            InfoOutput = false
        }
    })
    InfoOutput = self.db.profile.InfoOutput

    local panel = CreateFrame("Frame", TankHappyLocal, InterfaceOptionsFramePanelContainer)
    panel.name = TankHappyLocal
    if InterfaceOptions_AddCategory then
        InterfaceOptions_AddCategory(panel)
    else
        local category = Settings.RegisterCanvasLayoutCategory(panel, TankHappyLocal)
        Settings.RegisterAddOnCategory(category)
        panel.categoryID = category:GetID()
    end

    local content = CreateFrame("Frame", nil, panel)
    content:SetPoint("TOPLEFT", panel, "TOPLEFT", 16, -16)
    content:SetPoint("BOTTOMRIGHT", panel, "BOTTOMRIGHT", -16, 16)

    local title = content:CreateFontString(nil, "ARTWORK", "GameFontNormalHuge")
    title:SetPoint("TOP", 0, 0)
    title:SetText(TankHappyLocal)

    local subtitle = content:CreateFontString(nil, "ARTWORK", "GameFontNormal")
    subtitle:SetPoint("TOPLEFT", 0, -40)
    subtitle:SetJustifyH("LEFT")
    subtitle:SetText("根据你当前的职业，自动选择|TInterface\\Icons\\Ability_Hunter_Misdirection:16|t|CFFAAD372误导|r、|TInterface\\Icons\\Ability_Rogue_TricksOfTheTrade:16|t|CFFFFF468嫁祸|r、|TInterface\\Icons\\Spell_Nature_SkinofEarth:16|t|CFF0070DD大地之盾|r的目标。")

    local UseTitle = content:CreateFontString(nil, "ARTWORK", "GameFontNormalHuge")
    UseTitle:SetPoint("TOPLEFT", subtitle, "BOTTOMLEFT", 0, -30)
    UseTitle:SetText("使用方法")

    local UseText = content:CreateFontString(nil, "ARTWORK", "GameFontNormal")
    UseText:SetPoint("TOPLEFT", UseTitle, "BOTTOMLEFT", 0, -10)
    UseText:SetText("依次按下|CFFFFD700Ctrl+A|r、|CFFFFD700Ctrl+C|r复制以下宏命令，新建一个宏，拖到动作栏中使用。")
    local macroFrame = CreateFrame("EditBox", nil, content)
    macroFrame:SetSize(300, 40)
    macroFrame:SetPoint("TOPLEFT", UseTitle, "BOTTOMLEFT", 0, -35)
    macroFrame:SetMultiLine(true)
    macroFrame:SetAutoFocus(false)
    macroFrame:SetText("/click TankHappy LeftButton 1\n/click TankHappy LeftButton 0")
    macroFrame:SetFontObject("GameFontHighlight")
    macroFrame:EnableMouse(true)
    macroFrame:SetScript("OnEditFocusGained", function(self) 
        self:HighlightText() 
        self:SetCursorPosition(0)
    end)
    macroFrame:SetScript("OnMouseDown", function(self)
        if not self:HasFocus() then
            self:SetFocus()
            self:HighlightText()
        end
    end)
    macroFrame:SetScript("OnEscapePressed", function(self) self:ClearFocus() end)
    macroFrame:SetScript("OnEnterPressed", function(self) self:ClearFocus() end)
    macroFrame:SetScript("OnEnter", function(self)
        GameTooltip:SetOwner(self, "ANCHOR_TOPLEFT")
        GameTooltip:SetText("你可以在此宏的基础上改造更多的宏功能")
        GameTooltip:Show()
    end)
    macroFrame:SetScript("OnLeave", function() GameTooltip:Hide() end)
    local background = CreateFrame("Frame", nil, macroFrame, "BackdropTemplate")
    background:SetBackdrop({
        bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
        edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
        tile = true, tileSize = 16, edgeSize = 16,
        insets = { left = 4, right = 4, top = 4, bottom = 4 }
    })
    background:SetBackdropColor(0, 0, 0, 0.5)
    background:SetPoint("TOPLEFT", macroFrame, -5, 5)
    background:SetPoint("BOTTOMRIGHT", macroFrame, 5, -5)

    local UseTips = content:CreateFontString(nil, "ARTWORK", "GameFontNormal")
    UseTips:SetPoint("TOPLEFT", macroFrame, "BOTTOMLEFT", 0, -20)
    UseTips:SetJustifyH("LEFT")
    UseTips:SetText("根据当前的队伍状态智能选择目标，施放职业对应的法术。\n|CFFAAD372猎人|r |TInterface\\Icons\\Ability_Hunter_Misdirection:16|t误导坦克或宠物、|CFFFFF468潜行者|r |TInterface\\Icons\\Ability_Rogue_TricksOfTheTrade:16|t嫁祸坦克。\n|CFF0070DD萨满|r默认对坦克施放|TInterface\\Icons\\Spell_Nature_SkinofEarth:16|t大地之盾；有元素缠绕天赋时，战斗外先对自己施放，再次点击\n对坦克施放；战斗中对坦克施放。")

    local OptionTitle = content:CreateFontString(nil, "ARTWORK", "GameFontNormalHuge")
    OptionTitle:SetPoint("TOPLEFT", UseTips, "BOTTOMLEFT", 0, -30)
    OptionTitle:SetText("选项")

    local infoOutputCheck = CreateFrame("CheckButton", nil, content, "InterfaceOptionsCheckButtonTemplate")
    infoOutputCheck:SetPoint("TOPLEFT", OptionTitle, 0, -30)
    infoOutputCheck.Text:SetText("启用信息输出")
    infoOutputCheck:HookScript("OnClick", function()
        self.db.profile.InfoOutput = infoOutputCheck:GetChecked()
        InfoOutput = self.db.profile.InfoOutput
    end)
    infoOutputCheck:HookScript("OnEnter", function()
        GameTooltip:SetOwner(infoOutputCheck, "ANCHOR_TOPRIGHT")
        GameTooltip:SetText("启用后将在聊天窗口输出智能目标选择信息")
        GameTooltip:Show()
    end)
    infoOutputCheck:HookScript("OnLeave", function() GameTooltip:Hide() end)
    infoOutputCheck:SetChecked(self.db.profile.InfoOutput)
end