EpicMusicPlayerTitan = LibStub("AceAddon-3.0"):NewAddon("EpicMusicPlayerTitan", "AceEvent-3.0")
local L = LibStub("AceLocale-3.0"):GetLocale("EpicMusicPlayerTitan")

local songlength = 0
local songtitle = ""
local artist = ""
local album = ""
local listname = ""
local shorttitle = ""
local titleoffset = 0
local volumechanged = nil
local sec = 0
local playing = false;
local EpicMusicPlayerTitanText = "Stopped"

local options={
			name="Titan Panel",
			order = 7,
			type="group",
			args = {		
			    number = {
					type = 'toggle',
					--width = "half",
					order = 4,
					name = L['Show List/Song Numbers'],
					desc = L['Show playlist and song number'],
					get = function()
						return EpicMusicPlayerTitan.db.profile.shownumber
					end,
					set = function()
					    EpicMusicPlayerTitan.db.profile.shownumber = not EpicMusicPlayerTitan.db.profile.shownumber
						EpicMusicPlayerTitan:UpdateText()
					end,
				},
			    title = {
					type = 'toggle',
					--width = "half",
					order = 5,
					name = L['Show Title'],
					desc = L['Toggle show title'],
					get = function()
						return EpicMusicPlayerTitan.db.profile.showtitle
					end,
					set = function()
					    EpicMusicPlayerTitan.db.profile.showtitle = not EpicMusicPlayerTitan.db.profile.showtitle
					    EpicMusicPlayerTitan:UpdateText()
					end,
				},
			    showtime = {
		            type = "toggle",
		            order = 6,
				    name = L["Show time"],
		            desc = L["Toggle show time"],
		            get = function()
						return EpicMusicPlayerTitan.db.profile.showtime
					end,
					set = function()
					    EpicMusicPlayerTitan.db.profile.showtime = not EpicMusicPlayerTitan.db.profile.showtime
					    EpicMusicPlayerTitan:UpdateText()
					end,
		        },
				maxtextlength = {
					type = 'range',
					order = 8,
					name = L["Max song text length"],
					desc = L["The maximum text length of the song displayed in the Panel."],
					min = 4,
					max = 40,
					step = 1,
					get = function(name)
						return EpicMusicPlayerTitan.db.profile.MaxTextLength
					end,
					set = function(arg1,arg2)
						EpicMusicPlayerTitan:SetMaxTextLength(arg2)
					end,
				},	
			}
}

local function GetTimeSTring(seconds)
    local min = seconds / 60
		local sec = mod(seconds, 60)
		if( sec < 10) then
		    -- add zero 
        return string.format("%d:0%d", min, sec)
    end
		return string.format("%d:%d", min, sec)
end

function EpicMusicPlayerTitan:SetMaxTextLength(length)
   
   if length > 40 then
      self.db.profile.MaxTextLength = 40
      return
   end
   if length < 4 then
      self.db.profile.MaxTextLength = 4
      return
   end
   self.db.profile.MaxTextLength = length
   shorttitle = self:SetTextLenght(songtitle)
   self:UpdateText()
   
end

function EpicMusicPlayerTitan:SetTextLenght(text)
	local length = text:len()
	local maxLength = self.db.profile.MaxTextLength
	if length > maxLength then
		text = text:sub(1, maxLength - 3) .. '...'
	end
	
	return text
end

function EpicMusicPlayerTitan:OnInitialize()

	self.db = LibStub("AceDB-3.0"):New("EpicMusicPlayerTitanDB", defaults, "Default")
	
	self.db:RegisterDefaults({
		profile = {
			MaxTextLength = 20,
			showtime = true,
			scroll = false,
			showtitle = true,
			shownumber = false,
		},
	})
	self:RegisterMessage("EMPUpdateStop")
	self:RegisterMessage("EMPUpdatePlay")
	self:RegisterMessage("EMPUpdateTime")
	self:RegisterMessage("EMPUpdateVolume")
	EpicMusicPlayer:AddOptions("titan",options)
	
end

function EpicMusicPlayerTitan:OnLoad(self)
	self.registry = { 
		id = "EpicMusicPlayer",
		menuText = "EpicMusicPlayer",
		buttonTextFunction = "EpicMusicPlayerTitanPlugin_GetButtonText",
		tooltipTitle = "EpicMusicPlayer",
		--tooltipTextFunction = "EpicMusicPlayerTitanPlugin_GetTooltipText",
		tooltipCustomFunction = EpicMusicPlayerTitan.SetTooltip;
		frequency = 1, 
		icon = "Interface\\AddOns\\EpicMusicPlayerTitan\\icon",
		iconWidth = 16,
		savedVariables = {
			ShowIcon = 1
		}
	};
	--EpicMusicPlayer_TitanPluginLoaded = 1;
	--EpicMusicPlayerTitanText = "EpicMusicPlayer";
	--getglobal(this:GetName().."Text"):SetText(EpicMusicPlayerTitanText);
end

--/script TitanPanel_RemoveButton("EpicMusicPlayer");

function EpicMusicPlayerTitan:EMPUpdateStop()
	playing = false
	self:UpdateText()
end

function EpicMusicPlayerTitan:EMPUpdateVolume(event, voltype, vol)
	if(voltype == "done")then
		volumechanged = false
	else
		volumechanged = voltype
	end
	self:UpdateText()
end

function EpicMusicPlayerTitan:EMPUpdateTime(event)
	sec = sec +1
	self:UpdateText()
end

function EpicMusicPlayerTitan:EMPUpdatePlay(event, artistname, songname, length)
	volumechanged = false
	songlength = length
	songtitle = songname
	shorttitle = self:SetTextLenght(songtitle)
	album = EpicMusicPlayer:GetCurrentAlbumName()
	listname = EpicMusicPlayer:GetListName()
	artist = artistname
	playing = true
	titleoffset = 0
	sec = 0
	self:UpdateText()
end

function EpicMusicPlayerTitan:SetTooltip()
     --GameTooltip:SetOwner(parent, "ANCHOR_BOTTOMRIGHT");
	local emp = EpicMusicPlayer
	
	if(playing)then		
		GameTooltip:SetText(songtitle,1,1,1);
		--GameTooltip:AddDoubleLine(artist, songtitle, 1, 0.8, 0, 1, 1, 1);
		GameTooltip:AddLine(" ")
		GameTooltip:AddDoubleLine(L["Artist"], artist, 1, 0.8, 0, 1, 1, 1);
		if(album=="")then
		else
			GameTooltip:AddDoubleLine(L["Album"], album, 1, 0.8, 0, 1, 1, 1);
			
		end
		GameTooltip:AddDoubleLine(L["List"], listname, 1, 0.8, 0, 1, 1, 1);
		GameTooltip:AddDoubleLine(L["Length"], GetTimeSTring(songlength), 1, 0.8, 0, 1, 1, 1);
		GameTooltip:Show()
	else
		GameTooltip:SetText("EpicMusicPlayer - "..L["Stopped"], 1,1,1)
		GameTooltip:AddLine(" ")
		GameTooltip:AddLine(L["Left click"].." - "..emp.controlslist[emp.db.profile.controlset.left], 0,1,0)
		GameTooltip:AddLine(L["Middle click"].." - "..emp.controlslist[emp.db.profile.controlset.middle], 0,1,0)
		GameTooltip:AddLine(L["Right click"].." - "..emp.controlslist[emp.db.profile.controlset.right], 0,1,0)
		GameTooltip:AddLine(L["Use scroll wheel - adjust music volume"], 0,1,0)
		GameTooltip:AddLine(" ")
		GameTooltip:AddLine(L["Ctrl + use scroll wheel - adjust effects volume"], 0,1,0)
		GameTooltip:AddLine(L["Alt + use scroll wheel - fine adjust volume"], 0,1,0)
		GameTooltip:AddLine(L["Alt click"].." - "..emp.controlslist[emp.db.profile.controlset.leftalt], 0,1,0)
		GameTooltip:AddLine(L["Shift click"].." - "..emp.controlslist[emp.db.profile.controlset.leftshift], 0,1,0)
		GameTooltip:AddLine(L["Ctrl click"].." - "..emp.controlslist[emp.db.profile.controlset.leftcontrol], 0,1,0)
		GameTooltip:Show()
	end
end

function EpicMusicPlayerTitan:UpdateText()
   
    if(volumechanged) then
        if(volumechanged == "music")then
			EpicMusicPlayerTitanText = L["Music volume: "]..math.floor((EpicMusicPlayer.db.profile.volume*100)).."%"
			TitanPanelButton_UpdateButton("EpicMusicPlayer");
			return
		else
			EpicMusicPlayerTitanText = L["Effects volume: "]..math.floor((GetCVar("Sound_SFXVolume")*100)).."%"
			TitanPanelButton_UpdateButton("EpicMusicPlayer");
			return
		end
    end
	
    
	local text = ""
	if(self.db.profile.shownumber)then
		text = EpicMusicPlayer.db.profile.list.."/"..(EpicMusicPlayer.db.profile.song-1).." "
	end
	
	if(self.db.profile.showtitle or self.db.profile.showtime)then
		local title
	    if (playing == true) then
	  
			if(self.db.profile.showtitle) then
				text = text..shorttitle
			end
	        if(self.db.profile.showtime) then
				text = text.." "..GetTimeSTring(sec).."/"
					..GetTimeSTring(songlength)
			end      
	    else
			    text = text..L["Stopped"]
		end
	end
	
	EpicMusicPlayerTitanText = text;
	TitanPanelButton_UpdateButton("EpicMusicPlayer");
end

function EpicMusicPlayerTitanPlugin_GetButtonText()
	return EpicMusicPlayerTitanText;
end