SimplePowerBar = LibStub("AceAddon-3.0"):NewAddon("SimplePowerBar", "AceConsole-3.0")--, "AceEvent-3.0")
local Media = LibStub("LibSharedMedia-3.0")
local db;
local Addon = GetAddOnMetadata("SimplePowerBar", "Title")
local unit
local perc
local power, mpower

--PlayerPowerBarAlt:SetAlpha(0)
PlayerPowerBarAlt:HookScript("OnShow", function(self,...) 
	self:Hide()
end)


function SimplePowerBar:CreatePowerBar()
	db = self.db.profile
	local frame = self.frame
	local SimplePowerBarBG = CreateFrame("Frame", "SimplePowerBarBG", frame)
	SimplePowerBarBG:SetFrameStrata(db.frameStrata)
	SimplePowerBarBG:SetFrameLevel(db.frameLevel)
	SimplePowerBarBG:SetHeight(db.height)
	SimplePowerBarBG:SetWidth(db.width)
	SimplePowerBarBG:SetPoint("CENTER",UIParent,"CENTER", db.x, db.y)
	SimplePowerBarBG:SetBackdrop({
		bgFile = db.PanelTex, 
		edgeFile = db.PanelTex, 
		tile = false, tileSize = 0, edgeSize = db.borderSize, 
		insets = { left = db.borderInset, right = db.borderInset, top = db.borderInset, bottom = db.borderInset}
	})
	
	SimplePowerBarBG:SetMovable(true)
	SimplePowerBarBG:SetClampedToScreen(true)
	SimplePowerBarBG:SetUserPlaced(true)
	
	local SimplePowerBarLock = SimplePowerBarBG:CreateTexture("SimplePowerBarLock","OVERLAY",nil)
	SimplePowerBarLock:SetTexture("Interface\\GLUES\\CharacterSelect\\Glues-AddOn-Icons")
	SimplePowerBarLock:SetWidth(8)
	SimplePowerBarLock:SetHeight(8)	
	SimplePowerBarLock:SetTexCoord(0.25,0.48,0,1)
	SimplePowerBarLock:SetAlpha(1)
	SimplePowerBarLock:SetPoint("CENTER",SimplePowerBarBG,"TOPRIGHT")
	
	local SimplePowerBarStatus = CreateFrame("StatusBar", "SimplePowerBarStatus", SimplePowerBarBG)
	SimplePowerBarStatus:SetPoint("TOPLEFT", SimplePowerBarBG, "TOPLEFT", 1, -1)
	SimplePowerBarStatus:SetPoint("BOTTOMRIGHT", SimplePowerBarBG, "BOTTOMRIGHT", -1, 1)	
		
	local SimplePowerBarText = SimplePowerBarStatus:CreateFontString("SimplePowerBarText", "OVERLAY")
		
	local SimplePowerBarLabel = SimplePowerBarStatus:CreateFontString("SimplePowerBarLabel", "OVERLAY")
end

function SimplePowerBar:Unlock()
	db = self.db.profile
	SimplePowerBarBG:RegisterForDrag("LeftButton")
	SimplePowerBarBG:SetScript("OnDragStart", SimplePowerBarBG.StartMoving)
	SimplePowerBarBG:SetScript("OnDragStop", function()
		SimplePowerBarBG:StopMovingOrSizing()
		db.anchor,_,_,db.x,db.y = SimplePowerBarBG:GetPoint()		
	end)
	SimplePowerBarBG:Show()
	SimplePowerBarBG:EnableMouse(true)
	SimplePowerBarLock:SetAlpha(1)
end
	
function SimplePowerBar:Lock()
	SimplePowerBarBG:SetScript("OnDragStart", nil)
	SimplePowerBarBG:SetScript("OnDragStop", nil)
	if not UnitAlternatePowerInfo(unit) then
		SimplePowerBarBG:Hide()
	end
	SimplePowerBarBG:EnableMouse(false)
	SimplePowerBarLock:SetAlpha(0)
end

function SimplePowerBar:StatusBarUpdate(unit,power,mpower)
	db = self.db.profile
	SimplePowerBarStatus:SetMinMaxValues(0, UnitPowerMax(unit, ALTERNATE_POWER_INDEX))
	SimplePowerBarStatus:SetValue(power)
	if db.fade then
		local r,g,b
		local pct
		if power > 0 then
			pct = power/mpower
		else
			pct = 0
		end
		if power < (mpower/2) then
			r = (pct*2)
			g = 1
			b = 0
		else
			r = 1
			g = 1-((pct-0.5)*2)
			b = 0
		end
		SimplePowerBarStatus:SetStatusBarColor(r,g,b)
	else
		local color = SimplePowerBar.db.profile.StatusColor
		SimplePowerBarStatus:SetStatusBarColor(color.r,color.g,color.b)
	end
end

function SimplePowerBar:LabelTextUpdate(unit)
	db = self.db.profile
	if UnitAlternatePowerInfo(unit) and db.label then
		SimplePowerBarLabel:SetText(select(10,UnitAlternatePowerInfo(unit)))
	else
		SimplePowerBarLabel:SetText("")
	end
end

function SimplePowerBar:ValueTextUpdate(power,mpower)
	db = self.db.profile
	
	if power < 0 then power = 0 end -- Disables Negative values for power
	if db.amount then
		if db.level and db.percent then
			if mpower > 0 then
				SimplePowerBarText:SetText(power.."/"..mpower.." - "..floor((power/mpower)*100).."%")
			else
				SimplePowerBarText:SetText(power.."/"..mpower)
			end
		elseif db.level and not db.percent then
			SimplePowerBarText:SetText(power.."/"..mpower)
		elseif not db.level and db.percent then 
			SimplePowerBarText:SetText(floor((power/mpower)*100).."%")
		else
			SimplePowerBarText:SetText("")
		end
	else
		SimplePowerBarText:SetText("")
	end
end

function SimplePowerBar:Update() -- Only called on events where alternate power is changed.
	db = self.db.profile
	if not SimplePowerBarBG:IsShown() then SimplePowerBarBG:Show() end -- Automatically shows the frame.
	
	if not unit or unit ~= PlayerPowerBarAlt.unit then unit = PlayerPowerBarAlt.unit end
	power, mpower = UnitPower(unit, ALTERNATE_POWER_INDEX), UnitPowerMax(unit, ALTERNATE_POWER_INDEX)
	
	self:LabelTextUpdate(unit)
	self:ValueTextUpdate(power,mpower)
	self:StatusBarUpdate(unit,power,mpower)
	
	if db.locked then
		self:Lock()
	else
		self:Unlock()
	end
end
	
function SimplePowerBar:FullUpdate()
	db = self.db.profile
	
	-- StatusBar
	SimplePowerBarStatus:SetStatusBarTexture(Media:Fetch("statusbar",db.StatusTex))
	SimplePowerBarStatus:SetOrientation(db.Orientation)
	-- BarBG
	SimplePowerBarBG:SetBackdrop({
		bgFile = db.PanelTex, 
		edgeFile = db.PanelTex, 
		tile = false, tileSize = 0, edgeSize = db.borderSize, 
		insets = { left = db.borderInset, right = db.borderInset, top = db.borderInset, bottom = db.borderInset}
	})
	SimplePowerBarBG:SetBackdropColor(db.BackgroundColor.r,db.BackgroundColor.g,db.BackgroundColor.b,db.BackgroundColor.a)
	SimplePowerBarBG:SetBackdropBorderColor(db.BorderColor.r,db.BorderColor.g,db.BorderColor.b,db.BorderColor.a)
	SimplePowerBarBG:SetHeight(db.height)
	SimplePowerBarBG:SetWidth(db.width)
	SimplePowerBarBG:ClearAllPoints()
	SimplePowerBarBG:SetPoint(db.anchor,UIParent,db.anchor, db.x, db.y)
	SimplePowerBarBG:SetFrameStrata(db.frameStrata)
	SimplePowerBarBG:SetFrameLevel(db.frameLevel)
	--BarText
	SimplePowerBarText:SetFont(Media:Fetch("font", db.StatusBarText.font), db.StatusBarText.size, db.StatusBarText.style)
	SimplePowerBarText:ClearAllPoints()
	SimplePowerBarText:SetPoint(db.StatusBarText.align, SimplePowerBarBG, db.StatusBarText.anchor, db.StatusBarText.ofx, db.StatusBarText.ofy)
	SimplePowerBarText:SetShadowColor(0,0,0,db.StatusBarText.shadow)
	SimplePowerBarText:SetShadowOffset(db.StatusBarText.shadowOffset,-(db.StatusBarText.shadowOffset))
	-- Label
	SimplePowerBarLabel:SetFont(Media:Fetch("font", db.LabelText.font), db.LabelText.size, db.LabelText.style)
	SimplePowerBarLabel:ClearAllPoints()
	SimplePowerBarLabel:SetPoint(db.LabelText.align, SimplePowerBarBG, db.LabelText.anchor, db.LabelText.ofx, db.LabelText.ofy)
	SimplePowerBarLabel:SetShadowColor(0,0,0,db.LabelText.shadow)
	SimplePowerBarLabel:SetShadowOffset(db.LabelText.shadowOffset,-(db.LabelText.shadowOffset))
	-- Lock
	self:Update()
end

function SimplePowerBar:OnInitialize()
	local defaults = {
		profile = {
			StatusTex = "SimplePowerBar",
			Orientation = "HORIZONTAL",
			PanelTex = [[Interface\AddOns\SimplePowerBar\Textures\Border.tga]],
			borderSize = 1,
			borderInset = 1,
			frameStrata = "MEDIUM",
			frameLevel = 1,
			anchor = "CENTER",
			width = 100,
			height = 16,
			x = 0,
			y = -170,
	-- Coloring config
			StatusBarText = {
				font = "Arial Narrow",
				size = 8,
				align = "CENTER",
				anchor = "CENTER",
				style = "NONE",
				shadow = 1,
				shadowOffset = 1,				
				ofx = 0,
				ofy = 0,
			},
			LabelText = {
				font = "Arial Narrow",
				size = 8,
				align = "BOTTOM",
				anchor = "TOP",
				style = "NONE",
				shadow = 1,
				shadowOffset = 1,
				ofx = 0,
				ofy = 2,
			},
			StatusColor = {
				r = 0,
				g = 1,
				b = 0,
				a = 1,
			},
			BorderColor = {
				r = 0,
				g = 0,
				b = 0,
				a = 1,
			},
			BackgroundColor = {
				r = 0.2,
				g = 0.2,
				b = 0.2,
				a = 0.5
			},
			amount = true,
			level = true,
			percent = true,
			label = true,
			locked = false,
			fade = true,
			debug = false,
		}
	}
	local db = LibStub("AceDB-3.0"):New("SimpPB_DB",defaults,"Default")
	self.db = db
	local RegisterCallback = db.RegisterCallback	
	RegisterCallback(self, "OnProfileChanged", "FullUpdate")
	RegisterCallback(self, "OnProfileCopied", "FullUpdate")
	RegisterCallback(self, "OnProfileReset", "FullUpdate")
	
	db = self.db.profile
	
	self:CreatePowerBar()
	self:SetUpInitialOptions()
	self:FullUpdate()
	self:Update()
	
	local commands = {}
	commands.lock = function()
		db.locked = not db.locked
		if db.locked then
			print(Addon..": Locked")
		else
			print(Addon..": Unlocked")		
		end
	end

	commands.fade = function()
		db.fade = not db.fade
		if db.fade then
			print(Addon..": Color fade enabled.")
		else
			print(Addon..": Color fade disabled.")
		end
	end

	commands.debug = function()
		db.debug = not db.debug
		if db.debug then
			print(Addon..": Debugging enabled.")
		else
			print(Addon..": Debugging disabled.")
		end
	end

	commands.help = function()
		print(Addon.." Commands available:")
		print("'/spb lock' -- Allows you to drag the frame and place it with the mouse or lock it in place.")
		print("'/spb fade' -- Allows the color to fade according to amount of power.")
		print("'/spb debug' -- Allows the debugging mode to be enabled or disabled.")	
		print("'/spb about' -- Shows additional information about the addon.")
	end

	commands.about = function()
		print(Addon..": Created by Suicidal Katt, based off of '|cffC495DDSmelly|r Power Bar' by Smelly.")
	end

	local function slashHandler(arg)
		local arg1, arg2, arg3 = strsplit(" ", arg, 3)
		if arg1 then
			if type(commands[arg1]) == "function" then
				commands[arg1](arg2)
				SimplePowerBar:FullUpdate()
			else
				print(Addon..": Type '/spb help' for a list of commands.")
				SimplePowerBar:OpenOptions()
			end
		end
	end
	SLASH_SIMPPB1 = "/spb"
	SlashCmdList["SIMPPB"] = slashHandler
end

local frame = CreateFrame("frame")
frame:RegisterEvent("ADDON_LOADED")
frame:SetScript("OnEvent", function(self,event,...)
	local arg1,arg2,arg3,arg4 = ...
	db = SimplePowerBar.db.profile
	if event == "ADDON_LOADED" and arg1 == "SimplePowerBar" then
		self:UnregisterEvent("ADDON_LOADED")
			
		self:RegisterEvent("UNIT_POWER_BAR_SHOW")
		self:RegisterEvent("UNIT_POWER_BAR_HIDE")
		self:RegisterEvent("UNIT_POWER")
		self:RegisterEvent("UNIT_MAXPOWER")
		self:RegisterEvent("PLAYER_REGEN_DISABLED")
		self:RegisterEvent("PLAYER_REGEN_ENABLED")
		
	elseif (event == "UNIT_POWER" or event == "UNIT_MAXPOWER") and arg2 == "ALTERNATE" then
		if not unit or unit ~= PlayerPowerBarAlt.unit then
			unit = PlayerPowerBarAlt.unit
		end
		
		if unit == arg1 then
			SimplePowerBar:Update()
		end		
	elseif event == "UNIT_POWER_BAR_SHOW" then
		self:RegisterEvent("UNIT_POWER")
		self:RegisterEvent("UNIT_MAXPOWER")
		SimplePowerBar:Update()
	elseif event == "UNIT_POWER_BAR_HIDE" then
		self:UnregisterEvent("UNIT_POWER")
		self:UnregisterEvent("UNIT_MAXPOWER")		
		if not UnitAlternatePowerInfo(unit) and db.locked then
			SimplePowerBarBG:Hide()
		end
	elseif event == "PLAYER_REGEN_DISABLED" or event == "PLAYER_REGEN_ENABLED" then		
		if not UnitAlternatePowerInfo(unit) and db.locked then
			SimplePowerBarBG:Hide()
		else
			if not SimplePowerBarBG:IsShown() then
				SimplePowerBarBG:Show()
			end
		end
	end
	if db.debug then
		if arg2 then
			print(event.." "..arg1.." "..arg2)
		elseif arg1 and not arg2 then
			print(event.." "..arg1)
		elseif not arg1 and not arg2 then
			print(event)
		end
	end
end)
SimplePowerBar.frame = frame