--EpicMusicPlayerFu by yess
--A Fubarplugin for EpicMusicPlayer

EpicMusicPlayerFu = Rock:NewAddon("EpicMusicPlayerFu", "LibFuBarPlugin-3.0", "LibRockConfig-1.0", "LibRockDB-1.0", "AceEvent-3.0")
local L = LibStub("AceLocale-3.0"):GetLocale("EpicMusicPlayerFu")

EpicMusicPlayerFu:SetFuBarOption('iconPath', [[Interface\AddOns\EpicMusicPlayerFu\icon]])
EpicMusicPlayerFu:SetFuBarOption('configType', "AceConfigDialog-3.0")
EpicMusicPlayerFu:SetFuBarOption('clickableTooltip', true)
EpicMusicPlayerFu:SetFuBarOption('tooltipType', "Tablet-2.0")

local tablet = AceLibrary("Tablet-2.0")
local frame
EpicMusicPlayerFu.textLengthLowerBound = 4
EpicMusicPlayerFu.textLengthUpperBound = 40

local songlength = 0
local songtitle = ""
local artist = ""
local album = ""
local listname = ""
local shorttitle = ""
local titleoffset = 0
local volumechanged = nil
local sec = 0

EpicMusicPlayerFu:SetDatabase("EpicMusicPlayerFuDB")
EpicMusicPlayerFu:SetDatabaseDefaults('profile', {
			MaxTextLength = 40,
			show = true,
			showtime = true,
			scroll = false;
			showtitle = true;
			shownumber = false;
			tooltip = {
				spam = true;
				options = true;
				move = true;
				short = false;
				artist = true;
				album = true;
				length = true;
				playlist = true;
			}
		})
		
EpicMusicPlayerFu.Options={
			name="Fubar",
			order = 6,
			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 EpicMusicPlayerFu.db.profile.shownumber
					end,
					set = function()
					    EpicMusicPlayerFu.db.profile.shownumber = not EpicMusicPlayerFu.db.profile.shownumber
						EpicMusicPlayerFu:UpdateFuBarText()
					end,
				},
			    title = {
					type = 'toggle',
					--width = "half",
					order = 5,
					name = L['Show Title'],
					desc = L['Toggle show title in fubar'],
					get = function()
						return EpicMusicPlayerFu.db.profile.showtitle
					end,
					set = function()
					    EpicMusicPlayerFu.db.profile.showtitle = not EpicMusicPlayerFu.db.profile.showtitle
					    EpicMusicPlayerFu:UpdateFuBarText()
					end,
				},
			    showtime = {
		            type = "toggle",
		            order = 6,
				    name = L["Show time"],
		            desc = L["Toggle show time"],
		            get = function()
						return EpicMusicPlayerFu.db.profile.showtime
					end,
					set = function()
					    EpicMusicPlayerFu.db.profile.showtime = not EpicMusicPlayerFu.db.profile.showtime
					    EpicMusicPlayerFu:UpdateFuBarText()
					end,
		        },
				--[[
				  ScrollTitle = {
			           type = "toggle",
			           name = "Scroll Title",
			           desc = "Scroll Title",
			           get = "IsScrollTitle",
			           set = "ToggleScrollTitle",
				},--]]
				maxtextlength = {
					type = 'range',
					order = 8,
					name = L["Max song text length"],
					desc = L["The maximum text length of the song displayed in FuBar."],
					min = EpicMusicPlayerFu.textLengthLowerBound,
					max = EpicMusicPlayerFu.textLengthUpperBound,
					step = 1,
					get = function(name)
						return EpicMusicPlayerFu:GetMaxTextLength()
					end,
					set = function(arg1,arg2)
						EpicMusicPlayerFu:SetMaxTextLength(arg2)
					end,
				},
				tooltip = {
		            type = 'group',
		            name = L["Tooltip"],
		            desc = L["Tooltip Settings"],
		            args = {
						options = {
		                    type = 'toggle',
		                    name = L["Options/Hints"],
		                    desc = L["Toggle show Options/Hints in tooltip"],
							get = function(name)
								return EpicMusicPlayerFu:IsTooltipOptions()
							end,
							set = function(name)
								EpicMusicPlayerFu:ToggleTooltipOptions()
							end,
		                },
		                moveto = {
		                    type = 'toggle',
		                    name = L["Playlists"],
		                    desc = L["Toggle show playlists in tooltip"],
							get = function(name)
								return EpicMusicPlayerFu:IsTooltipMove()
							end,
							set = function(name)
								EpicMusicPlayerFu:ToggleTooltipMove()
							end,
		                },
						spam = {
		                    type = 'toggle',
		                    name = L["Spam to chat"],
		                    desc = L["Toggle show spam to chat in tooltip"],
		                    get = function(name)
								return EpicMusicPlayerFu:IsTooltipSpam()
							end,
							set = function(name)
								EpicMusicPlayerFu:ToggleTooltipSpam()
							end,
		                },
						short = {
		                    type = 'toggle',
		                    name = L["Short Tooltip"],
		                    desc = L["Show short tooltip only artist and songname"],
		                    get = function(name)
								return EpicMusicPlayerFu.db.profile.tooltip.short
							end,
							set = function(name)
								EpicMusicPlayerFu.db.profile.tooltip.short = not EpicMusicPlayerFu.db.profile.tooltip.short
							end,
		                },
		            },
		        },
				-- default fubar options
				fubar = {
					type = "group",
					name = L["FuBar options"],
					desc = L["FuBar options"],
					disabled = function() return EpicMusicPlayerFu.IsFuBarMinimapAttached == nil end,
					args = {
						attachMinimap = {
							type = "toggle",
							name = L["Attach to minimap"],
							desc = L["Attach to minimap"],
							get = function(info)
								return EpicMusicPlayerFu:IsFuBarMinimapAttached()
							end,
							set = function(info, v)
								EpicMusicPlayerFu:ToggleFuBarMinimapAttached()
								EpicMusicPlayerFu.Options["FuBar.AttachMinimap"] = EpicMusicPlayerFu:IsFuBarMinimapAttached()
							end
						},
						hideIcon = {
							type = "toggle",
							name = L["Hide minimap/FuBar icon"],
							desc = L["Hide minimap/FuBar icon"],
							get = function(info) 
								return EpicMusicPlayerFu.Options["FuBar.HideMinimapButton"] 
							end,
							set = function(info, v)
								EpicMusicPlayerFu.Options["FuBar.HideMinimapButton"] = v
								if v then
									EpicMusicPlayerFu:Hide()
									--EpicMusicPlayerFu:ToggleFuBarMinimapAttached()
								else
									EpicMusicPlayerFu:Show()
									--EpicMusicPlayerFu.Options["FuBar.AttachMinimap"] = true
									EpicMusicPlayerFu:ToggleFuBarMinimapAttached()
								end
							end
						},
						showIcon = {
							type = "toggle",
							name = L["Show icon"],
							desc = L["Show icon"],
							get = function(info) return EpicMusicPlayerFu:IsFuBarIconShown() end,
							set = function(info, v) EpicMusicPlayerFu:ToggleFuBarIconShown() end,
							disabled = GetFuBarMinimapAttachedStatus
						},
						showText = {
							type = "toggle",
							name = L["Show text"],
							desc = L["Show text"],
							get = function(info) return EpicMusicPlayerFu:IsFuBarTextShown() end,
							set = function(info, v) EpicMusicPlayerFu:ToggleFuBarTextShown() end,
							disabled = GetFuBarMinimapAttachedStatus
						},
						position = {
							type = "select",
							name = L["Position"],
							desc = L["Position"],
							values = {LEFT = L["Left"], CENTER = L["Center"], RIGHT = L["Right"]},
							get = function() return EpicMusicPlayerFu:GetPanel() and EpicMusicPlayerFu:GetPanel():GetPluginSide(EpicMusicPlayerFu) end,
							set = function(info, val)
								if EpicMusicPlayerFu:GetPanel() and EpicMusicPlayerFu:GetPanel().SetPluginSide then
									EpicMusicPlayerFu:GetPanel():SetPluginSide(EpicMusicPlayerFu, val)
								end
							end,
							disabled = GetFuBarMinimapAttachedStatus
						},
					},
		},
	}
}


function EpicMusicPlayerFu:OnEnable()

	self:RegisterMessage("EMPUpdateStop")
	self:RegisterMessage("EMPUpdatePlay")
	self:RegisterMessage("EMPUpdateTime")
	self:RegisterMessage("EMPUpdateVolume")
  
  --EpicMusicPlayerFu:EpicMusicPlayer_Update("play")
  
  self.effectsvolumechanged = 0
  
  frame = EpicMusicPlayerFu:GetFrame()
  frame:EnableMouseWheel(1) 
  --frame:RegisterForClicks("LeftButtonUp,Button4Up")
  --frame:SetScript("OnMouseDown",EpicMusicPlayer:GetDisplayClickHandler())
  --frame:SetScript("OnMouseUp",function()
  --this:StopMovingOrSizing()
--			this.isMoving = false
 -- end)
  --frame:SetScript("OnClick",EpicMusicPlayer:GetDisplayClickHandler())
  frame:SetScript("OnMouseWheel", 
    function()
		EpicMusicPlayer:DisplyScrollHandler()
    end
    )

	EpicMusicPlayerFu.OpenMenu = function()
		--local arg1 = "RightButton" 
		EpicMusicPlayer:OnDisplayClick(EpicMusicPlayerFu:GetFrame())
	end
end

function EpicMusicPlayerFu:OnInitialize()
	--EpicMusicPlayerFu:SetFuBarOption('iconPath', [[Interface\Icons\INV_Misc_Gear_06]])
	--print(self:GetFuBarIcon())
	EpicMusicPlayer:AddOptions("fubar",EpicMusicPlayerFu.Options)
end

-- fubar options -------------------------------
function EpicMusicPlayerFu:IsScrollTitle()
    return self.db.profile.scroll
end

function EpicMusicPlayerFu:ToggleScrollTitle()
    self.db.profile.scroll = not self.db.profile.scroll
    self:UpdateFuBarText()
end

function EpicMusicPlayerFu:IsTooltipOptions()
    return self.db.profile.tooltip.options
end
 
function EpicMusicPlayerFu:ToggleTooltipOptions()
    self.db.profile.tooltip.options = not self.db.profile.tooltip.options
end

function EpicMusicPlayerFu:IsTooltipSpam()
    return self.db.profile.tooltip.spam
end
 
function EpicMusicPlayerFu:ToggleTooltipSpam()
    self.db.profile.tooltip.spam = not self.db.profile.tooltip.spam
end

function EpicMusicPlayerFu:IsShowTitle()
    return self.db.profile.showtitle
end
 
function EpicMusicPlayerFu:ToggleShowTitle()
    self.db.profile.showtitle = not self.db.profile.showtitle
	self:UpdateFuBarText()
end

function EpicMusicPlayerFu:IsTooltipMove()
    return self.db.profile.tooltip.move
end
 
function EpicMusicPlayerFu:ToggleTooltipMove()
    self.db.profile.tooltip.move = not self.db.profile.tooltip.move
end

function EpicMusicPlayerFu:GetMaxTextLength()
   return self.db.profile.MaxTextLength
end

function EpicMusicPlayerFu:SetMaxTextLength(length)
   
   if length > self.textLengthUpperBound then
      self.db.profile.MaxTextLength = self.textLengthUpperBound
      return
   end
   if length < self.textLengthLowerBound then
      self.db.profile.MaxTextLength = self.textLengthLowerBound
      return
   end
   self.db.profile.MaxTextLength = length
   shorttitle = self:SetTextLenght(songtitle)
   self:UpdateFuBarText()
   
end

function EpicMusicPlayerFu:GetMaxTest()
   return EpicMusicPlayer.AnimTest
end

function EpicMusicPlayerFu:SetMaxTest(length)
   EpicMusicPlayer.AnimTest = length
   
end

function EpicMusicPlayerFu:OnUpdateFuBarText()
   
    if(volumechanged) then
        if(volumechanged == "music")then
			self:SetFuBarText(L["Music volume: "]..math.floor((EpicMusicPlayer.db.profile.volume*100)).."%")
			return
		else
			self:SetFuBarText(L["Effects volume: "]..math.floor((GetCVar("Sound_SFXVolume")*100)).."%")
			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 (EpicMusicPlayer.Playing == true) then
	  
			if(self.db.profile.showtitle) then
				if(self.db.profile.scroll) then
					text = text..EpicMusicPlayerFu:ScrollText(songtitle)
				else
					text = text..shorttitle
				end
			end
	        if(self.db.profile.showtime) then
	            --self:SetFubarText(string.format("d%:%d", t, EpicMusicPlayer_PlayList[EpicMusicPlayer.db.profile.list][EpicMusicPlayer.db.profile.song].Length))
	            --self:SetFubarText(shorttitle.." "..EpicMusicPlayer_GetTimeSTring(EpicMusicPlayer.Sec).."/"..songlength)
				text = text.." "..EpicMusicPlayer:GetTimeSTring(sec).."/"
					..EpicMusicPlayer:GetTimeSTring(songlength)
			end
	        
	    else
			    text = text..L["Stopped"]
		end
	end
	
	self:SetFuBarText(text)
end


function EpicMusicPlayerFu:OnUpdateFuBarTooltip()
	local emp = EpicMusicPlayer

	EpicMusicPlayerFu.OpenMenu = function()
		emp:OnDisplayClick(EpicMusicPlayerFu:GetFrame())
	end

	if(emp.Playing == true) then
        local cat
		if(EpicMusicPlayerFu.db.profile.tooltip.short)then
			-- show only artist and song
			cat = tablet:AddCategory(
	               'text', L["Artist"],
	               'text2', L["Song"],
	               'columns', 2,
	               'child_text2R', 0,
	               'child_text2G', 1,
	               'child_text2B', 0
	           )
	       
	           cat:AddLine(
					'text', artist,
					'text2', songtitle,
					'func', function()
                        --EpicMusicPlayerScrollBar:Show()
						--EpicMusicPlayerListsScrollBar:Show()
			            self:Hide()
						EpicMusicPlayerPlaylistFrame:Show()
					end
				)
		else
			cat = tablet:AddCategory(
	               'text', L["Artist"],
	               'text2', L["Song"],
	               'text3', L["Album"],
	               'text4', L["Length"],
	               'text5', L["Playlist"],
	               'columns', 5,
	               'child_text2R', 0,
	               'child_text2G', 1,
	               'child_text2B', 0
	           )
	       
	           cat:AddLine(
	               'text', artist,

	               'text2', songtitle,
	               'text3', album,
	               'text4', emp:GetTimeSTring(songlength),
	               'text5', listname,
					'func', function()
                        --EpicMusicPlayerScrollBar:Show()
						--EpicMusicPlayerListsScrollBar:Show()
			            EpicMusicPlayerPlaylistFrame:Show()
					end
			    )
		end
		
		
           
		----- show move to list --------------------------------------------------------------
		if(self:IsTooltipMove()) then 
			cat = tablet:AddCategory(
				'text', L["Play a list (alt+click move song)"],
				'columns', 1
			)

			-- move to list options
			local listnum = 1
			while (listnum <= table.getn(EpicMusicPlayer_PlayList)) do
				cat:AddLine(
					'text', "["..EpicMusicPlayer_PlayList[listnum][1].ListName.."]",
					'func', 'ListClicked',
					'arg1', self,
					'arg2', listnum
				)
				listnum = listnum + 1
			end
		end
			
		----- show spam to chat --------------------------------------------------------------
		if(self:IsTooltipSpam()) then 
			cat = tablet:AddCategory(
				'text', L["Spam to Chat:"],
				'columns', 1
			)
		
		  
			cat:AddLine(
               'text', L["[Guild]"],
                'textR', 0,
               'textG', 1,
               'textB', 0,
                'func', function()
                      emp:Spam("GUILD")
                end
			)
		  
			cat:AddLine(
               'text', L["[Party]"],
                'textR', 0.5,
               'textG', 0.5,
               'textB', 1,
                'func', function()
                      emp:Spam("PARTY")
                end
			)
		  
			cat:AddLine(
               'text', L["[Say]"],
                'textR', 1,
               'textG', 1,
               'textB', 1,
                'func', function()
                      emp:Spam("SAY")
                end
			)
		  
			local target = UnitName("target");
			local whisper = emp.whisper
			if(UnitIsPlayer("target")) then
				cat:AddLine(
				   'text', "["..L["To target"].." ("..target..")]",
					'textR', 1,
				   'textG', 0.5,
				   'textB', 1,
					'func', function()
						  emp:Spam("TARGET")
					end
				)
			end
			
			if(whisper)then
				cat:AddLine(
	               'text', "["..L["Whisper to"].." "..whisper.."]",
	                'textR', 1,
	               'textG', 0.5,
	               'textB', 1,
	                'func', function()
	                      emp:Spam("WHISPER")
	                end
				)
			end
			
			cat:AddLine(
               'text', L["[Raid]"],
                'textR', 1,
               'textG', 0.5,
               'textB', 0,
                'func', function()
                      emp:Spam("RAID")
                end
			)
		end

		----- show options--------------------------------------------------------------
		if(self:IsTooltipOptions()) then 		
			cat = tablet:AddCategory(
	              'text', L["Options/Hints"]..":",
	              'columns', 1
	        )
	          
	        cat:AddLine(
	               'text', emp.controlslist[emp.db.profile.controlset.left].."|cff00cc00 ("..L["Click"]..")",
				   --'text', L["Next song. |cff00cc00(Click)|r"],
	                'textR', 1,
	               'textG', 0.8,
	               'textB', 0,
	                'func', function()
	                      --EpicMusicPlayer:PlayNext()
						  emp[emp.db.profile.controlset.left](emp, frame)
	                end
	        )
	          
	        cat:AddLine(
	               'text', emp.controlslist[emp.db.profile.controlset.leftshift].."|cff00cc00 ("..L["Shift+Click"]..")",
	               'textR', 1,
	               'textG', 0.8,
	               'textB', 0,
	                 'func', function()
	                      --emp:PlayLast()
						  emp[emp.db.profile.controlset.leftshift](emp, frame)
	                end
	        )
	          
	        cat:AddLine(
	               'text', emp.controlslist[emp.db.profile.controlset.middle].."|cff00cc00 ("..L["Middle Click"]..")",
	               'textR', 1,
	               'textG', 0.8,
	               'textB', 0,
	                'func', function()
	                      emp[emp.db.profile.controlset.middle](emp, frame)
	                end
	        )
	          
	        cat:AddLine(
	                'text', emp.controlslist[emp.db.profile.controlset.leftalt].."|cff00cc00 ("..L["Alt+Click"]..")",
	                'textR', 1,
	                'textG', 0.8,
	                'textB', 0,
	                 'func', function() 
						emp[emp.db.profile.controlset.leftalt](emp, frame)
	                end
	        )
			
			cat:AddLine(
	                'text', emp.controlslist[emp.db.profile.controlset.leftaltcontrol].."|cff00cc00 ("..L["Alt+Ctrl+Click"]..")",
	                'textR', 1,
	                'textG', 0.8,
	                'textB', 0,
	                 'func', function() 
						emp[emp.db.profile.controlset.leftaltcontrol](emp, frame)
	                end
	        )
	          
	        cat:AddLine(
	                'text', "|cff00cc00"..L["Scroll over Fubar text to adjust music volume."].."|r",
	                'textR', 1,
	                'textG', 0.8,
	                'textB', 0
	        )
		end
    else -- not playing, show only hint
          local cat = tablet:SetHint(L["Click to play next song. Middlelick to toggle play/stop."])
    end    
end

-- a list was clicked in tooltip
function EpicMusicPlayerFu:ListClicked(arg1)
    if(IsAltKeyDown())then
		--move the song
		EpicMusicPlayer:MoveSong(EpicMusicPlayer.db.profile.list,arg1,EpicMusicPlayer.db.profile.song)
		listname = EpicMusicPlayer_PlayList[arg1][1].ListName
	else
		--play the list 
		EpicMusicPlayer.db.profile.list = arg1
		EpicMusicPlayer.db.profile.song = 1
		EpicMusicPlayer:PlayNext();
	end
end

--todo
function EpicMusicPlayerFu:OnFuBarMouseDown(button)
	EpicMusicPlayer:OnDisplayClick(frame)
end
 
function EpicMusicPlayerFu:OnFuBarClick()
	--EpicMusicPlayer:OnDisplayClick(frame)
end

function EpicMusicPlayerFu: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 EpicMusicPlayerFu:EMPUpdateVolume(event, voltype, vol)
	if(voltype == "done")then
		volumechanged = false
	else
		volumechanged = voltype
	end
	self:UpdateFuBarText()
end

function EpicMusicPlayerFu:EMPUpdateTime(event, arg1)
	sec = sec +1
	self:UpdateFuBarText()
end

function EpicMusicPlayerFu:EMPUpdateStop(event, arg1)
	self:UpdateFuBarPlugin()
end

function EpicMusicPlayerFu:EMPUpdatePlay(event, artistname, songname, slength)
	songlength = slength
	songtitle = songname
	shorttitle = self:SetTextLenght(songtitle)
	album = EpicMusicPlayer:GetCurrentAlbumName()
	listname = EpicMusicPlayer:GetListName()
	artist = artistname
	
	titleoffset = 0
	sec = 0
	self:UpdateFuBarPlugin() 
end

function EpicMusicPlayerFu:ScrollText(text)
    local maxLength = self.db.profile.MaxTextLength
	local textlen = text:len()
	if(textlen < maxLength) then
		return text
	else
		text = text.."      "..text
		text = text:sub(titleoffset, titleoffset+maxLength)
		titleoffset = titleoffset+1
		if(titleoffset > textlen+6) then
			titleoffset = 0
		end
	end
	return text
end

function print(text)
    DEFAULT_CHAT_FRAME:AddMessage(tostring(text))
end
