----------------------------------------------------------------------------------------
--  LootFrame based on Butsu
----------------------------------------------------------------------------------------
local T, C, L, _ = unpack(select(2, ...))

local addon = CreateFrame("Button", "Butsu")
local title = addon:CreateFontString(nil, "OVERLAY")
addon:CreateBackdrop()
addon:CreateShadow()
addon:CreateBorder()

local iconSize = C.Module.Loot.icon_size

local sq, ss, sn

local OnEnter = function(self)
	self.glow:Show()

	local slot = self:GetID()
	if(LootSlotHasItem(slot)) then
		GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
		GameTooltip:SetLootItem(slot)
		CursorUpdate(self)
	end

	LootFrame.selectedSlot = self:GetID()
end

local OnLeave = function(self)
	self.glow:Hide()
	GameTooltip:Hide()
	ResetCursor()
end

local OnClick = function(self)
	if(IsModifiedClick()) then
		HandleModifiedItemClick(GetLootSlotLink(self:GetID()))
	else
		StaticPopup_Hide"CONFIRM_LOOT_DISTRIBUTION"
		ss = self:GetID()
		sq = self.quality
		sn = self.name:GetText()
		LootSlot(ss)
	end
end

local OnUpdate = function(self)
	if(GameTooltip:IsOwned(self)) then
		GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
		GameTooltip:SetLootItem(self:GetID())
		CursorOnUpdate(self)
	end
end

local createSlot = function(id)
	local iconsize = iconSize
	local frame = CreateFrame("Button", "ButsuSlot"..id, addon)
	frame:SetPoint("LEFT", 5, 0)
	frame:SetPoint("RIGHT", -5, 0)
	frame:SetHeight(iconsize)
	frame:SetID(id)
	frame:CreateTwinkling()

	frame:RegisterForClicks("LeftButtonUp", "RightButtonUp")

	frame:SetScript("OnEnter", OnEnter)
	frame:SetScript("OnLeave", OnLeave)
	frame:SetScript("OnClick", OnClick)
	frame:SetScript("OnUpdate", OnUpdate)
	
	local iconFrame = CreateFrame("Frame", tostring(frame:GetName()).."IconFrame", frame)
	iconFrame:SetHeight(iconsize)
	iconFrame:SetWidth(iconsize)
	iconFrame:ClearAllPoints()
	iconFrame:SetPoint("LEFT", frame)
	iconFrame:CreateBackdrop()
	frame.iconFrame = iconFrame
	
	local icon = iconFrame:CreateTexture(nil, "ARTWORK")
	icon:SetAlpha(.8)
	icon:SetTexCoord(.07, .93, .07, .93)
	icon:SetPoint("TOPLEFT", 2, -2)
	icon:SetPoint("BOTTOMRIGHT", -2, 2)
	frame.icon = icon

	local count = iconFrame:CreateFontString(nil, "OVERLAY")
	count:ClearAllPoints()
	count:SetJustifyH("RIGHT")
	count:SetPoint("BOTTOMRIGHT", iconFrame, -1, 2)
	count:SetFont(STANDARD_TEXT_FONT, 12, "OUTLINE")
	count:SetShadowOffset(1, 1)
	count:SetShadowColor(.3, .3, .3, .7)
	count:SetText(1)
	frame.count = count

	local name = frame:CreateFontString(nil, "OVERLAY")
	name:SetJustifyH("LEFT")
	name:ClearAllPoints()
	name:SetPoint("RIGHT", frame)
	name:SetPoint("LEFT", icon, "RIGHT", 5, 0)
	name:SetNonSpaceWrap(true)
	name:SetFont(STANDARD_TEXT_FONT, 12, "OUTLINE")
	name:SetShadowOffset(1, -1)
	name:SetShadowColor(.3, .3, .3, .7)
	frame.name = name

	local glow = frame:CreateTexture(nil, "ARTWORK")
	glow:SetAlpha(.4)
	glow:SetPoint("TOPLEFT", icon, "TOPRIGHT", 2, 0)
	glow:SetPoint("BOTTOMRIGHT", frame)
	glow:SetTexture("Interface\\Buttons\\WHITE8x8")
	glow:SetVertexColor(.8, .8, 0)
	glow:Hide()
	frame.glow = glow
	
	addon.slots[id] = frame
	return frame
end

local anchorSlots = function(self)
	local iconsize = iconSize
	local shownSlots = 0
	for i=1, #self.slots do
		local frame = self.slots[i]
		if(frame:IsShown()) then
			shownSlots = shownSlots + 1

			-- We don't have to worry about the previous slots as they're already hidden.
			frame:SetPoint("TOP", addon, 0, ( -5 + iconsize) - (shownSlots * iconsize) - (shownSlots - 1) * 5)
		end
	end

	self:SetHeight(math.max(shownSlots * iconsize + 10 + ( shownSlots - 1) * 5 , iconsize))
end

title:SetFont(STANDARD_TEXT_FONT, 14, "OUTLINE")
title:SetShadowOffset(1, -1)
title:SetShadowColor(.3, .3, .3, .7)
title:SetPoint("BOTTOMLEFT", addon, "TOPLEFT", 4, 4)

addon:SetScript("OnMouseDown", function(self) if(IsAltKeyDown()) then self:StartMoving() end end)
addon:SetScript("OnMouseUp", function(self) self:StopMovingOrSizing() end)
addon:SetScript("OnHide", function(self)
	StaticPopup_Hide"CONFIRM_LOOT_DISTRIBUTION"
	CloseLoot()
end)
addon:SetMovable(true)
addon:RegisterForClicks("anyup")

addon:SetParent(UIParent)
addon:SetPoint(unpack(C.Module.Loot.pos))
addon:SetWidth(256)
addon:SetHeight(64)

addon:SetClampedToScreen(true)
addon:SetClampRectInsets(0, 0, 14, 0)
addon:SetHitRectInsets(0, 0, -14, 0)
addon:SetFrameStrata("HIGH")
addon:SetToplevel(true)

local chn = { "say", "party", "guild", "raid"}
local chnc = {
	{1, 1, 1, .7},
	{.1, .5, .7, .7},
	{0, .8, 0, .7},
	{.85, .2, .1, .7},
}
local pos = {
	{"TOPRIGHT", Butsu, "BOTTOM", -28, -5},
	{"TOPRIGHT", Butsu, "BOTTOM", -2, -5},
	{"TOPLEFT", Butsu, "BOTTOM", 2, -5},
	{"TOPLEFT", Butsu, "BOTTOM", 28, -5},
}

local function Announce(chn)
    local nums = GetNumLootItems()
    if(nums == 0) then return end
    if UnitIsPlayer("target") or not UnitExists("target") then -- Chests are hard to identify!
		SendChatMessage(L.LOOT_CHEST..":", chn)
	else
		SendChatMessage(L.LOOT_MONSTER.."'"..UnitName("target").."'", chn)
	end
    for i = 1, GetNumLootItems() do
        if(LootSlotHasItem(i)) then
            local link = GetLootSlotLink(i)
            local messlink = "- %s"

            if GetLootSlotType(i) ~= LOOT_SLOT_MONEY then
				SendChatMessage(format(messlink, link), chn)
			end
        end
    end
end

local AnnounceButton = {}
for i = 1, #chn do
	AnnounceButton[i] = CreateFrame("Button", "AnnounceButton"..i, Butsu)
	AnnounceButton[i]:SetSize(22, 14)
    AnnounceButton[i]:SetPoint(unpack(pos[i]))
    --AnnounceButton[i]:CreateBackdrop()
    --AnnounceButton[i]:CreateShadow()
    AnnounceButton[i]:CreateBorder()

    AnnounceButton[i].texture = AnnounceButton[i]:CreateTexture(nil, "ARTWORK")
    AnnounceButton[i].texture:SetTexture(C.Media.Texture.status)
    AnnounceButton[i].texture:SetVertexColor(unpack(chnc[i]))
    AnnounceButton[i].texture:SetPoint("TOPLEFT", AnnounceButton[i], "TOPLEFT", 1, -1)
    AnnounceButton[i].texture:SetPoint("BOTTOMRIGHT", AnnounceButton[i], "BOTTOMRIGHT", -1, 1)

	AnnounceButton[i].highlight = AnnounceButton[i]:CreateTexture(nil, "HIGHLIGHT")
	AnnounceButton[i].highlight:SetTexture(unpack(C.Media.highlight_color))
	AnnounceButton[i].highlight:SetAllPoints(AnnounceButton[i].texture)

	AnnounceButton[i]:SetScript("OnClick", function() Announce(chn[i]) end)
end

addon.slots = {}
addon.LOOT_OPENED = function(self, event, autoloot)
	self:Show()

	if(not self:IsShown()) then
		CloseLoot(not autoLoot)
	end

	local items = GetNumLootItems()

	if(IsFishingLoot()) then
		title:SetText(L.LOOT_FISH)
	elseif(not UnitIsFriend("player", "target") and UnitIsDead("target")) then
		title:SetText(UnitName("target"))
	else
		title:SetText(LOOT)
	end

	-- Blizzard uses strings here
	if(GetCVar("lootUnderMouse") == "1") then
		local x, y = GetCursorPosition()
		x = x / self:GetEffectiveScale()
		y = y / self:GetEffectiveScale()

		self:ClearAllPoints()
		self:SetPoint("TOPLEFT", nil, "BOTTOMLEFT", x - 40, y + 20)
		self:GetCenter()
		self:Raise()
	end

	local m, w, t = 0, 0, title:GetStringWidth()
	if(items > 0) then
		for i=1, items do
			local slot = addon.slots[i] or createSlot(i)
			local texture, item, quantity, quality, locked = GetLootSlotInfo(i)
			local color = ITEM_QUALITY_COLORS[quality] or {1, 1, 1}

			if GetLootSlotType(i) == LOOT_SLOT_MONEY then
				item = item:gsub("\n", ", ")
			end

			if(quantity and quantity > 1) then
				slot.count:SetText(quantity)
				slot.count:Show()
			else
				slot.count:Hide()
			end
			
			if(quality and quality > 0) then
				slot.iconFrame:SetBackdropBorderColor(color.r, color.g, color.b)
			else
				slot.iconFrame:SetBackdropBorderColor(0, 0, 0)
			end

			slot.quality = quality
			slot.name:SetText(item)
			slot.name:SetTextColor(color.r, color.g, color.b)
			slot.icon:SetTexture(texture)
			w = math.max(w, slot.name:GetStringWidth())
			
			slot:Enable()
			slot:Show()
		end
	else
		local slot = addon.slots[1] or createSlot(1)
		local color = ITEM_QUALITY_COLORS[0]

		slot.name:SetText(EMPTY)
		slot.name:SetTextColor(color.r, color.g, color.b)
		slot.icon:SetTexture(nil)

		items = 1
		w = math.max(w, slot.name:GetStringWidth())

		slot.count:Hide()
		slot:Disable()
		slot:Show()
	end
	anchorSlots(self)

	w = w + 70
	t = t + 15

	self:SetWidth(math.max(w, t))
end

addon.LOOT_SLOT_CLEARED = function(self, event, slot)
	if(not self:IsShown()) then return end

	addon.slots[slot]:Hide()
	anchorSlots(self)
end

addon.LOOT_CLOSED = function(self)
	StaticPopup_Hide("LOOT_BIND")
	self:Hide()

	for _, v in pairs(self.slots) do
		v:Hide()
	end
end

addon.OPEN_MASTER_LOOT_LIST = function(self)
	ToggleDropDownMenu(1, nil, GroupLootDropDown, addon.slots[ss], 0, 0)
end

addon.UPDATE_MASTER_LOOT_LIST = function(self)
	UIDropDownMenu_Refresh(GroupLootDropDown)
end

addon:SetScript("OnEvent", function(self, event, ...)
	self[event](self, event, ...)
end)

addon:RegisterEvent("LOOT_OPENED")
addon:RegisterEvent("LOOT_SLOT_CLEARED")
addon:RegisterEvent("LOOT_CLOSED")
addon:RegisterEvent("OPEN_MASTER_LOOT_LIST")
addon:RegisterEvent("UPDATE_MASTER_LOOT_LIST")
addon:Hide()

-- Fuzz
LootFrame:UnregisterAllEvents()
table.insert(UISpecialFrames, "Butsu")

function _G.GroupLootDropDown_GiveLoot(self)
	if ( sq >= MASTER_LOOT_THREHOLD ) then
		local dialog = StaticPopup_Show("CONFIRM_LOOT_DISTRIBUTION", ITEM_QUALITY_COLORS[sq].hex..sn..FONT_COLOR_CODE_CLOSE, self:GetText())
		if (dialog) then
			dialog.data = self.value
		end
	else
		GiveMasterLoot(ss, self.value)
	end
	CloseDropDownMenus()
end

StaticPopupDialogs["CONFIRM_LOOT_DISTRIBUTION"].OnAccept = function(self, data)
	GiveMasterLoot(ss, data)
end