local media = LibStub("LibSharedMedia-2.0")
local BC = AceLibrary("Babble-Class-2.2")

local max_unit_size = 5
local max_party_size = 4
local header_padding = 33
local partypadding_default = 5
local manapadding_default = 5
local highlight_padding = 10

local SendChatMessage = SendChatMessage

local classIcons = {
	["Warrior"] = {0, 0.25, 0, 0.25},
	["Mage"] = {0.25, 0.49609375, 0, 0.25},
	["Rogue"] = {0.49609375, 0.7421875, 0, 0.25},
	["Druid"] = {0.7421875, 0.98828125, 0, 0.25},
	["Hunter"] = {0, 0.25, 0.25, 0.5},
	["Shaman"] = {0.25, 0.49609375, 0.25, 0.5},
	["Priest"] = {0.49609375, 0.7421875, 0.25, 0.5},
	["Warlock"] = {0.7421875, 0.98828125, 0.25, 0.5},
	["Paladin"] = {0, 0.25, 0.5, 0.75},
}

function Proximo:MakeFrame()
	local barwidth = self.db.profile.barwidth
	local barheight = self.db.profile.barheight
	local padding = self.db.profile.padding
	local extrapadding = 0
	local ptpadding = 0
	partypadding_default = self.db.profile.partytargetheight + 1
	manapadding_default = self.db.profile.manaheight + 1
	if self.db.profile.partytargets then
		extrapadding = extrapadding + partypadding_default
		ptpadding = ptpadding + partypadding_default
	end
	if self.db.profile.mana then
		extrapadding = extrapadding + manapadding_default
	end
	
	self.frame=CreateFrame("Button", nil, UIParent)
	self.frame.owner = self
	self.frame:Hide()
	self.frame:SetWidth(barwidth+barheight+(padding*2)+8) 
	self.frame:SetHeight(((barheight+padding)*(max_unit_size))+4+header_padding+padding+(extrapadding*5)) 
	self.frame:SetScale(self.db.profile.scale)
	self.frame:ClearAllPoints()
	if self.db.profile.x==0 and self.db.profile.y==0 then
		self.frame:SetPoint("TOP", UIParent, "TOP")
	else
		local es = self.frame:GetEffectiveScale()
		self.frame:SetPoint("CENTER", UIParent, "CENTER", self.db.profile.x/es, self.db.profile.y/es)
	end
	self.frame:SetBackdrop({
		bgFile = "Interface\\Tooltips\\UI-Tooltip-Background", tile = true, tileSize = 16,
		edgeFile = "Interface\\AddOns\\Proximo\\Textures\\otravi-semi-full-border", edgeSize = 32,
		insets = {left = 1, right = 1, top = 30, bottom = 1},
	})
	self.frame:SetBackdropColor(self.db.profile.framecolor.r,self.db.profile.framecolor.g,self.db.profile.framecolor.b,self.db.profile.framecolor.a)
	self.frame:SetBackdropBorderColor(1,1,1,0)
	self.frame:EnableMouse(true)
	self.frame:SetMovable(true)
	self.frame:RegisterForDrag("LeftButton")
	self.frame:RegisterForClicks("RightButtonUp")
	self.frame:SetScript(
		'OnClick', function()
		   if not InCombatLockdown() and not self:ArenaStarted() then self:DewDropMenu() end
		end
	)
	self.frame:SetScript(
		'OnDragStart', function()
			if not InCombatLockdown() and IsAltKeyDown() then this:StartMoving() end
		end
	)
	self.frame:SetScript(
		'OnDragStop', function()
				if not InCombatLockdown() then
				this:StopMovingOrSizing()
				local x, y = this:GetCenter()
				local es = this:GetEffectiveScale()
				local ps = UIParent:GetScale()
				x = x*es - GetScreenWidth()*ps/2
				y = y*es - GetScreenHeight()*ps/2
				this.owner.db.profile.x, this.owner.db.profile.y = x, y
			end
		end
	)
	
	self.frame.text = self.frame:CreateFontString(nil, "OVERLAY")
	self.frame.text:ClearAllPoints()
	self.frame.text:SetWidth(barwidth)
	self.frame.text:SetHeight(header_padding)
	self.frame.text:SetPoint("TOP", self.frame, "TOP", 0, -5)
	self.frame.text:SetFont(media:Fetch("font", self.db.profile.font), 16)
	self.frame.text:SetJustifyH("CENTER")
	self.frame.text:SetText("")
	self.frame.text:SetShadowOffset(1, -1)
	self.frame.text:SetShadowColor(0, 0, 0, 1)
	
	--set up header settings
	if (self.db.profile.header) then
		self.frame:SetBackdropBorderColor(1,1,1,1)
		self.frame.text:SetText(self.title)
	end
	
	self.frame.buttons={}
	for i=1,max_unit_size do
		local b=CreateFrame("Button", "ProximoTarget"..i, self.frame, "SecureActionButtonTemplate")
		b:SetHeight(barheight)
		b:SetWidth(barwidth+barheight)
		b:ClearAllPoints()
		if i==1 then
			b:SetPoint("TOP",self.frame,"TOP", 0, -padding-header_padding-ptpadding)
		else
			b:SetPoint("TOP",self.frame.buttons[i-1],"BOTTOM", 0, -padding-extrapadding)
		end
		b:RegisterForClicks("LeftButtonUp", "RightButtonUp")
		b:SetAttribute("*type*", "macro")
		b:SetAttribute("macrotext1", "/script PlaySound(\"igQuestLogAbandonQuest\")")
		b:SetAttribute("macrotext2", "/script PlaySound(\"igQuestLogAbandonQuest\")")
		
		b.healthBar = CreateFrame("StatusBar", "HealthBar", b)
		b.healthBar:ClearAllPoints()
		b.healthBar:SetPoint("TOPLEFT",b,"TOPLEFT", barheight, 0)
		b.healthBar:SetPoint("BOTTOMRIGHT",b,"BOTTOMRIGHT")
		b.healthBar:SetStatusBarTexture(media:Fetch('statusbar', self.db.profile.texture))
		b.healthBar:SetMinMaxValues(0, 100)
		b.healthBar:SetValue(0)
		
		b.healthBar.bg = b.healthBar:CreateTexture(nil, "BACKGROUND")
		b.healthBar.bg:ClearAllPoints()
		b.healthBar.bg:SetAllPoints(b.healthBar)
		b.healthBar.bg:SetTexture(media:Fetch('statusbar', self.db.profile.texture))
		b.healthBar.bg:SetVertexColor(0.3, 0.3, 0.3)
		b.healthBar.bg:SetAlpha(0.3)
		b.healthBar.bg:Hide()
		
		b.healthBar.highlight = CreateFrame("Frame", "Highlight", b.healthBar)
		if self.db.profile.highlight == "tooltip" then
			highlight_padding = 10
			b.healthBar.highlight:SetBackdrop({
				edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", edgeSize = 16,
				insets = {left = 4, right = 4, top = 4, bottom = 4},
			})
		elseif self.db.profile.highlight == "solid" then
			highlight_padding = 4
			b.healthBar.highlight:SetBackdrop({
				edgeFile = "Interface\\ChatFrame\\ChatFrameBackground", edgeSize = 1,
				insets = {left = 0, right = 0, top = 0, bottom = 0},
			})
		end
		b.healthBar.highlight:SetBackdropBorderColor(self.db.profile.highlightcolor.r,self.db.profile.highlightcolor.g,self.db.profile.highlightcolor.b,0)
		b.healthBar.highlight:SetHeight(barheight+highlight_padding+extrapadding)
		b.healthBar.highlight:SetWidth(barwidth+highlight_padding)
		b.healthBar.highlight:ClearAllPoints()
		b.healthBar.highlight:SetPoint("TOP",b.healthBar,"TOP", 0, (highlight_padding/2)+ptpadding)
		
		b.healthBar.selected = b.healthBar:CreateTexture(nil, "OVERLAY")
		b.healthBar.selected:SetTexture("Interface\\QuestFrame\\UI-QuestTitleHighlight")
		b.healthBar.selected:SetBlendMode("ADD")
		b.healthBar.selected:SetAlpha(0.5)
		b.healthBar.selected:ClearAllPoints()
		b.healthBar.selected:SetAllPoints(b.healthBar)
		b.healthBar.selected:Hide()
		
		b.text = b.healthBar:CreateFontString(nil,"LOW")
		b.text:SetFont(media:Fetch("font", self.db.profile.font), self.db.profile.fontsize)
		b.text:SetShadowOffset(1, -1)
	  b.text:SetShadowColor(0, 0, 0, 1)
		b.text:SetJustifyH("LEFT")
		b.text:ClearAllPoints()
		b.text:SetAllPoints(b.healthBar)
		
		b.healthtext = b.healthBar:CreateFontString(nil,"LOW")
		b.healthtext:SetFont(media:Fetch("font", self.db.profile.font), self.db.profile.fontsize)
		b.healthtext:SetShadowOffset(1, -1)
	  b.healthtext:SetShadowColor(0, 0, 0, 1)
		b.healthtext:SetJustifyH("RIGHT")
		b.healthtext:ClearAllPoints()
		b.healthtext:SetAllPoints(b.healthBar)
		
		b.icon = b:CreateTexture(nil, "ARTWORK")
		b.icon:ClearAllPoints()
		b.icon:SetHeight(barheight)
		b.icon:SetWidth(barheight)
		b.icon:SetPoint("TOPLEFT",b,"TOPLEFT",-1,0)
		
		self:CreateManaBar(b)

		table.insert(self.frame.buttons,b)
	end
	self:CreatePartyTargets()
end


function Proximo:UpdateFrame()
	--if no frame made, then make it instead of update.
	if not self.frame then
		return
	end

	local barwidth = self.db.profile.barwidth
	local barheight = self.db.profile.barheight
	local padding = self.db.profile.padding
	local extrapadding = 0
	local ptpadding = 0
	partypadding_default = self.db.profile.partytargetheight + 1
	manapadding_default = self.db.profile.manaheight + 1
	if self.db.profile.partytargets then
		extrapadding = extrapadding + partypadding_default
		ptpadding = ptpadding + partypadding_default
	end
	if self.db.profile.mana then
		extrapadding = extrapadding + manapadding_default
	end
	
	self.frame:SetWidth(barwidth+barheight+(padding*2)+8)  
	self.frame:SetHeight(((barheight+padding)*(max_unit_size))+4+header_padding+padding+(extrapadding*5)) 
	self.frame:SetScale(self.db.profile.scale)
	self.frame:SetBackdropColor(self.db.profile.framecolor.r,self.db.profile.framecolor.g,self.db.profile.framecolor.b,self.db.profile.framecolor.a)
	self.frame:SetBackdropBorderColor(1,1,1,0)
	self.frame:ClearAllPoints()
	local s = self.frame:GetEffectiveScale()
	self.frame:SetPoint("CENTER", UIParent, "CENTER", self.db.profile.x/s, self.db.profile.y/s)
		
	self.frame.text:SetFont(media:Fetch("font", self.db.profile.font), 16)
	self.frame.text:SetWidth(barwidth)  
	self.frame.text:SetText("")
	
	if (self.db.profile.header) then
		self.frame:SetBackdropBorderColor(1,1,1,1)
		self.frame.text:SetText(self.title)
	end
	
	local i,j
	for i=1,max_unit_size do
		local b=self.frame.buttons[i]
		b:SetHeight(barheight)
		b:SetWidth(barwidth+barheight)
		b:ClearAllPoints()
		if i==1 then
			b:SetPoint("TOP",self.frame,"TOP", 0, -padding-header_padding-ptpadding)
		else
			b:SetPoint("TOP",self.frame.buttons[i-1],"BOTTOM", 0, -padding-extrapadding)
		end		
		b.healthBar:ClearAllPoints()
		b.healthBar:SetPoint("TOPLEFT",b,"TOPLEFT", barheight, 0)
		b.healthBar:SetPoint("BOTTOMRIGHT",b,"BOTTOMRIGHT")
		b.healthBar:SetStatusBarTexture(media:Fetch('statusbar', self.db.profile.texture))
		b.healthBar.bg:SetTexture(media:Fetch('statusbar', self.db.profile.texture))
		if self.db.profile.highlight == "tooltip" then
			highlight_padding = 10
			b.healthBar.highlight:SetBackdrop({
				edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", edgeSize = 16,
				insets = {left = 4, right = 4, top = 4, bottom = 4},
			})
		elseif self.db.profile.highlight == "solid" then
			highlight_padding = 4
			b.healthBar.highlight:SetBackdrop({
				edgeFile = "Interface\\ChatFrame\\ChatFrameBackground", edgeSize = 1,
				insets = {left = 0, right = 0, top = 0, bottom = 0},
			})
		end
		b.healthBar.highlight:SetBackdropBorderColor(self.db.profile.highlightcolor.r,self.db.profile.highlightcolor.g,self.db.profile.highlightcolor.b,0)
		b.healthBar.highlight:SetHeight(barheight+highlight_padding+extrapadding)
		b.healthBar.highlight:SetWidth(barwidth+highlight_padding)
		b.healthBar.highlight:SetPoint("TOP",b.healthBar,"TOP", 0, (highlight_padding/2)+ptpadding)
		b.text:SetFont(media:Fetch("font", self.db.profile.font), self.db.profile.fontsize)
		b.healthtext:SetFont(media:Fetch("font", self.db.profile.font), self.db.profile.fontsize)
		b.icon:SetHeight(barheight)
		b.icon:SetWidth(barheight)
		if self.db.profile.partytargets then
			if b.partytargets then
				for j=1,max_party_size do
					b.partytargets[j]:SetWidth((barwidth/max_party_size)-1)
					b.partytargets[j]:SetHeight(self.db.profile.partytargetheight)
					if j==1 then
						b.partytargets[j]:ClearAllPoints()
						b.partytargets[j]:SetPoint("BOTTOMLEFT",b,"TOPLEFT",barheight,1)
					end
				 	b.partytargets[j]:SetStatusBarTexture(media:Fetch('statusbar', self.db.profile.texture))
				 	b.partytargets[j].bg:SetTexture(media:Fetch('statusbar', self.db.profile.texture))
				 	b.partytargets[j]:Show()
				end
			else
				self:CreatePartyTargets()
			end
		elseif b.partytargets then
			for j=1,max_party_size do
				b.partytargets[j]:Hide()
			end
		end
		if self.db.profile.mana then
			if b.manaBar then
				b.manaBar:SetWidth(barwidth)
				b.manaBar:SetHeight(self.db.profile.manaheight)
				b.manaBar:SetStatusBarTexture(media:Fetch('statusbar', self.db.profile.texture))
				b.manaBar:SetStatusBarColor(self.db.profile.manacolor.r,self.db.profile.manacolor.g,self.db.profile.manacolor.b,1)
				b.manaBar.bg:SetVertexColor(self.db.profile.manacolor.r,self.db.profile.manacolor.g,self.db.profile.manacolor.b)
			else
				self:CreateManaBar(b)
			end
		elseif b.manaBar then
			b.manaBar:Hide()
		end
	end
	
	self:FrameRefresh()
end

function Proximo:CreatePartyTargets()
	local i,j, pt
	if self.db.profile.partytargets then
		for i=1,max_unit_size do
			local b=self.frame.buttons[i]
			local barwidth = self.db.profile.barwidth
			local barheight = self.db.profile.barheight
			b.partytargets={}
			for j=1,max_party_size do
				pt = CreateFrame("StatusBar", "PartyBar", b)
				pt:ClearAllPoints()
				if j==1 then
					pt:SetPoint("BOTTOMLEFT",b,"TOPLEFT",barheight,1)
					pt:SetWidth((barwidth/max_party_size))
				else
					pt:SetPoint("TOPLEFT",b.partytargets[j-1],"TOPRIGHT",1,0)
					pt:SetWidth((barwidth/max_party_size)-1)
				end
				pt:SetHeight(self.db.profile.partytargetheight)
			 	pt:SetStatusBarTexture(media:Fetch('statusbar', self.db.profile.texture))
				pt:SetMinMaxValues(0, 1)
				pt:SetValue(0)
				
				pt.bg = pt:CreateTexture(nil, "BACKGROUND")
				pt.bg:ClearAllPoints()
				pt.bg:SetAllPoints(pt)
				pt.bg:SetTexture(media:Fetch('statusbar', self.db.profile.texture))
				pt.bg:SetVertexColor(.7,.7,.7)
				pt.bg:SetAlpha(0.3)
				
				pt:Hide()
				table.insert(b.partytargets,pt)
			end
		end
	end
end

function Proximo:CreateManaBar(frame)
	if self.db.profile.mana and not frame.manaBar then
		frame.manaBar = CreateFrame("StatusBar", "ManaBar", frame)
		frame.manaBar:ClearAllPoints()
		frame.manaBar:SetHeight(self.db.profile.manaheight)
		frame.manaBar:SetWidth(frame.healthBar:GetWidth())
		frame.manaBar:SetPoint("TOPLEFT",frame.healthBar,"BOTTOMLEFT",0,-1)
		frame.manaBar:SetStatusBarTexture(media:Fetch('statusbar', self.db.profile.texture))
		frame.manaBar:SetStatusBarColor(self.db.profile.manacolor.r,self.db.profile.manacolor.g,self.db.profile.manacolor.b,1)
		frame.manaBar:SetMinMaxValues(0, 100)
		frame.manaBar:SetValue(0)
		
		frame.manaBar.bg = frame.manaBar:CreateTexture(nil, "BACKGROUND")
		frame.manaBar.bg:ClearAllPoints()
		frame.manaBar.bg:SetAllPoints(frame.manaBar)
		frame.manaBar.bg:SetTexture(media:Fetch('statusbar', self.db.profile.texture))
		frame.manaBar.bg:SetVertexColor(self.db.profile.manacolor.r,self.db.profile.manacolor.g,self.db.profile.manacolor.b)
		frame.manaBar.bg:SetAlpha(0.3)
		
		frame.manaBar:Hide()
	end
end

function Proximo:FrameClean()
	if not self.frame then return end
	--clean up all unit info
	local i,j
  for i=1,max_unit_size do
  	if self.frame.buttons[i] then
  		self.frame.buttons[i]:SetAttribute("macrotext1", "/script PlaySound(\"igQuestLogAbandonQuest\")")
			self.frame.buttons[i]:SetAttribute("macrotext2", "/script PlaySound(\"igQuestLogAbandonQuest\")")
  		self.frame.buttons[i].healthBar:SetValue(0)
  		self.frame.buttons[i].healthBar.bg:Hide()
  		self.frame.buttons[i].healthtext:SetText(nil)
  		self.frame.buttons[i].text:SetText(nil)
  		self.frame.buttons[i].icon:SetTexture(nil)
  		if self.frame.buttons[i].partytargets then
  			for j=1,max_party_size do
  				self.frame.buttons[i].partytargets[j]:SetValue(0)
  				self.frame.buttons[i].partytargets[j]:Hide()
  			end
  		end
  		if self.frame.buttons[i].manaBar then
  			self.frame.buttons[i].manaBar:SetValue(0)
  			self.frame.buttons[i].manaBar:Hide()
  		end
  	end
  end
end

function Proximo:FrameClass(frame,class)
	local r,g,b = BC:GetColor(class)
	frame.healthBar:SetStatusBarColor(r,g,b,1)
	frame.healthBar.bg:SetVertexColor(r,g,b)
	frame.healthBar.bg:Show()
	self:SetClassIcon(frame.icon, class)
	if frame.manaBar then
		if self.db.profile.mana and class ~= "Warrior" and class ~= "Rogue" then
			frame.manaBar:Show()
		else
			frame.manaBar:Hide()
		end
	end
end

function Proximo:SetClassIcon(texture, classname)
	local class = classIcons[classname]
	if class[1] and class[2] and class[3] and class[4] then
		texture:SetTexture("Interface\\Glues\\CharacterCreate\\UI-CharacterCreate-Classes")
		texture:SetTexCoord(class[1], class[2], class[3], class[4])
	else
		texture:SetTexture("Interface\\Icons\\INV_Misc_QuestionMark")
		texture:SetTexCoord(0,0,0,1,1,0,1,1)
	end
end

function Proximo:Test()
	self:ResetList()
	self:AddToList("Perseph", "Rogue", 100, 0)
	self:AddToList("Reznic", "Warlock", 76, 53)
	self:AddToList("Suun", "Priest", 54, 24)
	self:AddToList("Alynn", "Paladin", 21, 87)
	self:AddToList("Grayhoof", "Shaman", 59, 100)
	self:FrameRefresh()
	if self.db.profile.partytargets then
		local i, j, name, unit, button
		for i=1,max_unit_size do
			for j=1, max_party_size do
				self.frame.buttons[i].partytargets[j]:Show()
			end
		end
	end
end

----------------------
--Send Annoucement
function Proximo:SendAnnouncement(name, class)
	if self.db.profile.announce == "disabled" then 
		return
	end
	local r,g,b = BC:GetColor(class)
	local lclass = class
	if BC:HasTranslation(class) then lclass = BC[class] end
	if self.db.profile.announce == "chat" then
		self:Print("|cff"..BC:GetHexColor(class)..name.." ("..lclass..")|r")
	elseif self.db.profile.announce == "sct" and SCT then
		SCT:DisplayCustomEvent(name.." ("..lclass..")", {r=r,g=g,b=b}, 1, 1, 1)
	elseif self.db.profile.announce == "msbt" and MikSBT then
		MikSBT.DisplayMessage(name.." ("..lclass..")", MikSBT.DISPLAYTYPE_NOTIFICATION, true, r*255,g*255,b*255)
	elseif self.db.profile.announce == "party" then
		SendChatMessage(name.." ("..lclass..")", "PARTY")
	else
		RaidWarningFrame:SetTimeVisible(3)
		RaidWarningFrame:SetHeight(120)
		RaidWarningFrame:AddMessage(name.." ("..lclass..")", r,g,b)
	end
end