local layoutName = "BlizzTourney"
local layout = {}
layout.name = "|cff00b4ffBlizz|r Tourney"
local L = sArenaMixin.L

layout.defaultSettings = {
    posX = 330,
    posY = 140,
    scale = 1.3,
    classIconFontSize = 12,
    spacing = 20,
    growthDirection = 1,
    specIcon = {
        posX = 26,
        posY = 26,
        scale = 1,
    },
    trinket = {
        posX = 43,
        posY = -17,
        scale = 1,
        fontSize = 12,
    },
    racial = {
        posX = 74,
        posY = -17,
        scale = 1,
        fontSize = 12,
    },
    dispel = {
        posX = 74,
        posY = 12,
        scale = 1,
        fontSize = 12,
    },
    castBar = {
        posX = -100,
        posY = -18,
        scale = 1.2,
        width = 90,
        iconScale = 1,
        keepDefaultModernTextures = true,
        recolorCastbar = false,
    },
    dr = {
        posX = -79,
        posY = 6,
        size = 24,
        borderSize = 2.5,
        fontSize = 12,
        spacing = 6,
        growthDirection = 4,
    },
    widgets = {
        combatIndicator = {
            posX = 0,
            posY = 0,
            scale = 0.8,
        },
        healerIndicator = {
            posX = 0,
            posY = 0,
            scale = 1,
        },
        targetIndicator = {
            posX = 0,
            posY = 0,
            scale = 1,
            useBorder = false,
            useBorderWithIcon = false,
        },
        focusIndicator = {
            posX = 0,
            posY = 0,
            scale = 1,
            useBorder = false,
            useBorderWithIcon = false,
        },
        partyTargetIndicators = {
            partyOnArena = {
                enabled = true,
                posX = 0,
                posY = 0,
                scale = 1,
                direction = "LEFT",
                spacing = 0,
            },
            arenaOnParty = {
                enabled = true,
                posX = 0,
                posY = 0,
                scale = 1,
                direction = "LEFT",
                spacing = 0,
            },
        },
        partyTargetText = {
            partyOnArena = {
                enabled = true,
                anchor = "RIGHT",
                fontSize = 10,
                posX = 0,
                posY = 0,
            },
            arenaOnParty = {
                enabled = true,
                anchor = "RIGHT",
                fontSize = 10,
                posX = 0,
                posY = 0,
            },
        },
    },

    textures          = {
        generalStatusBarTexture       = "sArena Default",
        healStatusBarTexture          = "sArena Stripes",
        castbarStatusBarTexture       = "sArena Default",
        castbarUninterruptibleTexture = "sArena Default",
        bgTexture = "Solid",
        bgColor = {0, 0, 0, 0.6},
    },
    retextureHealerClassStackOnly = true,

    -- custom layout settings
    frameFont = "Prototype",
    cdFont  = "Prototype",
    mirrored = true,

    textSettings = {
        specNameSize = 0.70,
        nameAnchor = "RIGHT",
        powerAnchor = "RIGHT",
    },
}

local function getSetting(info)
    return layout.db[info[#info]]
end

local function setSetting(info, val)
    layout.db[info[#info]] = val

    for i = 1, info.handler.maxArenaOpponents do
        local frame = info.handler["arena" .. i]
        layout:UpdateOrientation(frame)
    end

    if info[#info] == "mirrored" then
        local expectedSpecIconPosX = val and (layout.defaultSettings.specIcon.posX - 47) or layout.defaultSettings.specIcon.posX
        local expectedTrinketPosX = val and (layout.defaultSettings.trinket.posX - 84) or layout.defaultSettings.trinket.posX

        if layout.db.specIcon.posX == expectedSpecIconPosX then
            if val then
                layout.db.specIcon.posX = layout.db.specIcon.posX + 47
            else
                layout.db.specIcon.posX = layout.db.specIcon.posX - 47
            end
            info.handler:UpdateSpecIconSettings(layout.db.specIcon)
        end

        if layout.db.trinket.posX == expectedTrinketPosX then
            if val then
                layout.db.trinket.posX = layout.db.trinket.posX + 84
            else
                layout.db.trinket.posX = layout.db.trinket.posX - 84
            end
            info.handler:UpdateTrinketSettings(layout.db.trinket)
        end
    end

    info.handler:RefreshConfig()
end

local function setupOptionsTable(self)
    layout.optionsTable = self:GetLayoutOptionsTable(layoutName)

    layout.optionsTable.arenaFrames.args.positioning.args.mirrored = {
        order = 5,
        name = L["Option_MirroredFrames"],
        type = "toggle",
        width = "full",
        get = getSetting,
        set = setSetting,
    }

    layout.optionsTable.arenaFrames.args.other.args.trinketCircleBorder = {
        order = 6,
        name = L["Option_TrinketCircleBorder"],
        desc = L["Option_TrinketCircleBorder_Desc"],
        type = "toggle",
        get = getSetting,
        set = setSetting,
    }

end

function layout:Initialize(frame)
    self.db = frame.parent.db.profile.layoutSettings[layoutName]

    if (not self.optionsTable) then
        setupOptionsTable(frame.parent)
    end

    if (frame:GetID() == frame.parent.maxArenaOpponents) then
        frame.parent:UpdateCastBarSettings(self.db.castBar)
        frame.parent:UpdateDRSettings(self.db.dr)
        frame.parent:UpdateFrameSettings(self.db)
        frame.parent:UpdateSpecIconSettings(self.db.specIcon)
        frame.parent:UpdateTrinketSettings(self.db.trinket)
        frame.parent:UpdateRacialSettings(self.db.racial)
        frame.parent:UpdateDispelSettings(self.db.dispel)
        frame.parent:UpdateWidgetSettings(self.db.widgets)
    end

    frame.ClassIcon.Cooldown:SetSwipeTexture("Interface\\CharacterFrame\\TempPortraitAlphaMask")
    frame.ClassIcon.Cooldown:SetUseCircularEdge(true)
    frame.ClassIcon:SetFrameStrata("LOW")
    frame.ClassIcon:SetFrameLevel(7)

    frame:SetSize(126, 66)
    frame.SpecIcon:SetSize(14, 14)
    frame.SpecIcon.Texture:AddMaskTexture(frame.SpecIcon.Mask)
    frame.Trinket:SetSize(25, 25)
    frame.Racial:SetSize(25, 25)
    frame.Dispel:SetSize(25, 25)

    frame.AuraStacks:SetPoint("BOTTOMLEFT", frame.ClassIcon, "BOTTOMLEFT", 1, -2)
    frame.AuraStacks:SetFont("Interface\\AddOns\\sArena_Reloaded\\Textures\\arialn.ttf", 14, "THICKOUTLINE")

    local hp = frame.HealthBar
    hp:SetSize(87, 23)
    hp:SetStatusBarTexture("Interface\\RaidFrame\\Raid-Bar-Hp-Fill")

    local pp = frame.PowerBar
    pp:SetSize(87, 12)
    pp:SetStatusBarTexture("Interface\\RaidFrame\\Raid-Bar-Resource-Fill")

    local f = frame.ClassIcon
    f:SetSize(34, 34)
    f:Show()
    f.Texture:AddMaskTexture(f.Mask)

    f.Mask:SetSize(34, 34)

    if not f.bgTexture then
        f.bgTexture = f:CreateTexture(nil, "BORDER", nil, -1)
    end
    f.bgTexture:SetAllPoints(f.Texture)
    f.bgTexture:SetColorTexture(0.1, 0.1, 0.1, 1)
    f.bgTexture:AddMaskTexture(f.Mask)
    f.bgTexture:Show()

    local trinket = frame.Trinket
    if self.db.trinketCircleBorder then
        frame.parent.showTrinketCircleBorder = true
        if not trinket.Mask then
            trinket.Mask = trinket:CreateMaskTexture()
        end
        trinket.Mask:SetTexture("Interface\\CharacterFrame\\TempPortraitAlphaMask", "CLAMPTOBLACKADDITIVE", "CLAMPTOBLACKADDITIVE")
        trinket.Mask:SetAllPoints(trinket.Texture)
        trinket.Texture:AddMaskTexture(trinket.Mask)

        trinket.Cooldown:SetSwipeTexture("Interface\\CharacterFrame\\TempPortraitAlphaMask")
        trinket.Cooldown:SetUseCircularEdge(true)

        if not trinket.CircleBorder then
            trinket.CircleBorder = trinket:CreateTexture(nil, "ARTWORK", nil, 3)
        end

        local trinketCircleBorder = trinket.CircleBorder
        trinketCircleBorder:ClearAllPoints()
        trinketCircleBorder:SetTexture("Interface\\CHARACTERFRAME\\TotemBorder")
        trinketCircleBorder:SetPoint("TOPLEFT", trinket, "TOPLEFT", -8, 8)
        trinketCircleBorder:SetPoint("BOTTOMRIGHT", trinket, "BOTTOMRIGHT", 8, -8)
        trinketCircleBorder:SetDrawLayer("OVERLAY", 7)
        trinketCircleBorder:Show()

        if not trinket.TrinketCircleBorderHook then
            hooksecurefunc(trinket.Texture, "SetTexture", function(self, t)
                if not t or not frame.parent.showTrinketCircleBorder then
                    trinketCircleBorder:Hide()
                else
                    trinketCircleBorder:Show()
                end
            end)
            trinket.TrinketCircleBorderHook = true
        end
    else
        if trinket.Mask then
            trinket.Texture:RemoveMaskTexture(trinket.Mask)
        end
        if trinket.CircleBorder then
            trinket.CircleBorder:Hide()
        end

        trinket.Cooldown:SetUseCircularEdge(false)
    end

    -- SpecIcon border (owned by SpecIcon)
    if not frame.SpecIcon.Border then
        frame.SpecIcon.Border = frame.SpecIcon:CreateTexture(nil, "ARTWORK", nil, 3)
    end

    local specBorder = frame.SpecIcon.Border
    specBorder:ClearAllPoints()
    specBorder:SetTexture("Interface\\CHARACTERFRAME\\TotemBorder")
    specBorder:SetPoint("TOPLEFT", frame.SpecIcon, "TOPLEFT", -5, 5)
    specBorder:SetPoint("BOTTOMRIGHT", frame.SpecIcon, "BOTTOMRIGHT", 5, -5)
    specBorder:Show()

    f = frame.CastBar
    f:SetStatusBarTexture("Interface\\RaidFrame\\Raid-Bar-Hp-Fill")

    f = frame.DeathIcon
    f:ClearAllPoints()
    f:SetPoint("CENTER", frame.HealthBar, "CENTER")
    f:SetSize(32, 32)

    frame.PowerBar:SetHeight(10)

    local fn, fs, fstyle = frame.HealthText:GetFont()
    frame.HealthText:SetFont(fn, fs, "OUTLINE")
    local fn, fs, fstyle = frame.HealthText:GetFont()
    frame.PowerText:SetFont(fn, fs, "OUTLINE")
    frame.PowerText:SetAlpha(frame.parent.db.profile.hidePowerText and 0 or 1)

    local fn, fs, fstyle = frame.SpecNameText:GetFont()
    frame.SpecNameText:SetFont(fn, fs, "OUTLINE")
    frame.SpecNameText:SetTextColor(1,1,1)

    local underlay = frame.TexturePool:Acquire()
    underlay:SetDrawLayer("BACKGROUND", 1)
    underlay:SetColorTexture(0, 0, 0, 0.75)
    underlay:SetPoint("TOPLEFT", hp, "TOPLEFT")
    underlay:SetPoint("BOTTOMRIGHT", pp, "BOTTOMRIGHT")
    underlay:Show()


    local frameTexture = frame.frameTexture
    frameTexture:ClearAllPoints()
    frameTexture:SetDrawLayer("ARTWORK", 2)
    frameTexture:SetSize(160, 80)
    frameTexture:SetAtlas("UnitFrame")
    frameTexture:SetPoint("CENTER", frame, "CENTER")
    frameTexture:Show()

    self:UpdateOrientation(frame)
end

function layout:UpdateOrientation(frame)
    local frameTexture = frame.frameTexture
    local healthBar = frame.HealthBar
    local powerBar = frame.PowerBar
    local classIcon = frame.ClassIcon
    local classIconMask = frame.ClassIcon.Mask
    local name = frame.Name
    local specName = frame.SpecNameText
    local healthText = frame.HealthText
    local powerText = frame.PowerText
    local castbarText = frame.CastBar.Text

    healthBar:ClearAllPoints()
    powerBar:ClearAllPoints()
    frame.ClassIcon:ClearAllPoints()
    classIconMask:ClearAllPoints()
    name:ClearAllPoints()

    if self.db.widgets then
        local w = self.db.widgets

        -- Combat Indicator
        if w.combatIndicator then
            frame.WidgetOverlay.combatIndicator:ClearAllPoints()
            frame.WidgetOverlay.combatIndicator:SetSize(18, 18)
            frame.WidgetOverlay.combatIndicator:SetScale(w.combatIndicator.scale or 1)
            frame.WidgetOverlay.combatIndicator:SetPoint("CENTER", frame.HealthBar, "CENTER",
                (w.combatIndicator.posX or 0), (w.combatIndicator.posY or 0) - 20)
        end

        -- Healer Indicator
        if w.healerIndicator then
            frame.WidgetOverlay.healerIndicator:ClearAllPoints()
            frame.WidgetOverlay.healerIndicator:SetSize(17, 17)
            frame.WidgetOverlay.healerIndicator:SetScale(w.healerIndicator.scale or 1)
            frame.WidgetOverlay.healerIndicator:SetPoint("BOTTOMLEFT", frame.HealthBar, "TOPLEFT",
                (w.healerIndicator.posX or 0) + 2, (w.healerIndicator.posY or 0) + 2.5)
        end

        -- Target Indicator
        if w.targetIndicator then
            frame.WidgetOverlay.targetIndicator:ClearAllPoints()
            frame.WidgetOverlay.targetIndicator:SetSize(34, 34)
            frame.WidgetOverlay.targetIndicator:SetScale(w.targetIndicator.scale or 1)
            frame.WidgetOverlay.targetIndicator:SetPoint("CENTER", frame.ClassIcon, "CENTER",
                (w.targetIndicator.posX or 0) - 10, (w.targetIndicator.posY or 0) - 17)
        end

        -- Focus Indicator
        if w.focusIndicator then
            frame.WidgetOverlay.focusIndicator:ClearAllPoints()
            frame.WidgetOverlay.focusIndicator:SetSize(20, 20)
            frame.WidgetOverlay.focusIndicator:SetScale(w.focusIndicator.scale or 1)
            frame.WidgetOverlay.focusIndicator:SetPoint("BOTTOMRIGHT", frame.ClassIcon, "BOTTOMRIGHT",
                (w.focusIndicator.posX or 0) - 25, (w.focusIndicator.posY or 0) - 3)
        end

        -- Party Target Indicators
        if w.partyTargetIndicators and w.partyTargetIndicators.partyOnArena then
            local poa = w.partyTargetIndicators.partyOnArena
            local direction = poa.direction or "LEFT"
            frame.WidgetOverlay.partyTarget1:ClearAllPoints()
            frame.WidgetOverlay.partyTarget1:SetSize(15, 15)
            frame.WidgetOverlay.partyTarget1:SetScale(poa.scale or 1)
            frame.WidgetOverlay.partyTarget1:SetPoint("TOPLEFT", frame.HealthBar, "TOPRIGHT",
                (poa.posX or 0) - 27, (poa.posY or 0) + 33)

            for i = 2, 4 do
                local indicator = frame.WidgetOverlay["partyTarget" .. i]
                indicator:SetSize(15, 15)
                indicator:SetScale(poa.scale or 1)
                sArenaMixin:ChainIndicator(indicator, frame.WidgetOverlay["partyTarget" .. (i - 1)], direction, poa.spacing or 3)
            end
        end
    end

    if self.db.textSettings then
        local txt = self.db.textSettings
        local modernCastbar = self.db.castBar.useModernCastbars

        name:SetScale(txt.nameSize or 1)
        healthText:SetScale(txt.healthSize or 1)
        specName:SetScale(txt.specNameSize or 1)
        castbarText:SetScale(txt.castbarSize or 1)
        powerText:SetScale(txt.powerSize or 1)

        -- Name
        name:ClearAllPoints()
        if (txt.nameAnchor or "CENTER") == "LEFT" then
            name:SetPoint("BOTTOMLEFT", frame.HealthBar, "TOPLEFT", 3 + (txt.nameOffsetX or 0), 5.5 + (txt.nameOffsetY or 0))
        elseif (txt.nameAnchor or "CENTER") == "RIGHT" then
            name:SetPoint("BOTTOMRIGHT", frame.HealthBar, "TOPRIGHT", -3 + (txt.nameOffsetX or 0), 5.5 + (txt.nameOffsetY or 0))
        else
            name:SetPoint("BOTTOM", frame.HealthBar, "TOP", (txt.nameOffsetX or 0), 5.5 + (txt.nameOffsetY or 0))
        end

        -- Health Text
        healthText:ClearAllPoints()
        if (txt.healthAnchor or "CENTER") == "LEFT" then
            healthText:SetPoint("LEFT", healthBar, "LEFT", (txt.healthOffsetX or 0), (txt.healthOffsetY or 0))
        elseif (txt.healthAnchor or "CENTER") == "RIGHT" then
            healthText:SetPoint("RIGHT", healthBar, "RIGHT", (txt.healthOffsetX or 0), (txt.healthOffsetY or 0))
        else
            healthText:SetPoint("CENTER", healthBar, "CENTER", (txt.healthOffsetX or 0), (txt.healthOffsetY or 0))
        end

        -- Power Text
        powerText:ClearAllPoints()
        if (txt.powerAnchor or "CENTER") == "LEFT" then
            powerText:SetPoint("LEFT", frame.PowerBar, "LEFT", 0 + (txt.powerOffsetX or 0), (txt.powerOffsetY or 0))
        elseif (txt.powerAnchor or "CENTER") == "RIGHT" then
            powerText:SetPoint("RIGHT", frame.PowerBar, "RIGHT", 0 + (txt.powerOffsetX or 0), (txt.powerOffsetY or 0))
        else
            powerText:SetPoint("CENTER", frame.PowerBar, "CENTER", (txt.powerOffsetX or 0), (txt.powerOffsetY or 0))
        end

        -- Spec Text
        specName:ClearAllPoints()
        if (txt.specNameAnchor or "CENTER") == "LEFT" then
            specName:SetPoint("LEFT", frame.PowerBar, "LEFT", (txt.specNameOffsetX or 0), (txt.specNameOffsetY or 0))
        elseif (txt.specNameAnchor or "CENTER") == "RIGHT" then
            specName:SetPoint("RIGHT", frame.PowerBar, "RIGHT", (txt.specNameOffsetX or 0), (txt.specNameOffsetY or 0))
        else
            specName:SetPoint("CENTER", frame.PowerBar, "CENTER", (txt.specNameOffsetX or 0), (txt.specNameOffsetY or 0))
        end

        -- Castbar Text
        castbarText:ClearAllPoints()
        local simpleCastbar = self.db.castBar.simpleCastbar and modernCastbar
        if (txt.castbarAnchor or "CENTER") == "LEFT" then
            castbarText:SetPoint("LEFT", frame.CastBar, "LEFT", 3 + (txt.castbarOffsetX or 0), (modernCastbar and (simpleCastbar and 0 or -11) or 0) + (txt.castbarOffsetY or 0))
        elseif (txt.castbarAnchor or "CENTER") == "RIGHT" then
            castbarText:SetPoint("RIGHT", frame.CastBar, "RIGHT", -3 + (txt.castbarOffsetX or 0), (modernCastbar and (simpleCastbar and 0 or -11) or 0) + (txt.castbarOffsetY or 0))
        else
            castbarText:SetPoint("CENTER", frame.CastBar, "CENTER", (txt.castbarOffsetX or 0), (modernCastbar and (simpleCastbar and 0 or -11) or 0) + (txt.castbarOffsetY or 0))
        end

        if txt.forceCastbarTextWidth then
            castbarText:SetWidth((self.db.castBar.width or frame.CastBar:GetWidth()) / (txt.castbarSize or 1))
        else
            castbarText:SetWidth(0)
        end
    end

    if (self.db.mirrored) then
        frameTexture:SetTexCoord(1, 0, 0, 1)
        frameTexture:SetPoint("TOPLEFT", frame, "TOPLEFT", -26, 6)

        healthBar:SetPoint("TOPLEFT", frame, "TOPLEFT", 3, -30)
        powerBar:SetPoint("TOPLEFT", frame, "TOPLEFT", 3, -53)
        frame.ClassIcon:SetPoint("TOPRIGHT", -2, -2)
        classIconMask:SetPoint("TOPRIGHT", -2, -2)

        --name:SetJustifyH("RIGHT")
    else
        frameTexture:SetTexCoord(0, 1, 0, 1)
        frameTexture:SetPoint("TOPLEFT", frame, "TOPLEFT", -7, 6)

        healthBar:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -2, -30)
        powerBar:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -2, -53)
        frame.ClassIcon:SetPoint("TOPLEFT", 3, -2)
        classIconMask:SetPoint("TOPLEFT", 3, -2)

        --name:SetJustifyH("LEFT")
    end

    name:SetJustifyV("BOTTOM")
    --name:SetPoint("BOTTOMLEFT", frame.HealthBar, "TOPLEFT", 5, 5)
    --name:SetPoint("BOTTOMRIGHT", frame.HealthBar, "TOPRIGHT", -5, 5)
    name:SetHeight(12)
end

sArenaMixin.layouts[layoutName] = layout
sArenaMixin.defaultSettings.profile.layoutSettings[layoutName] = layout.defaultSettings
