
--SET OF INITIAL VARIABLES THAT ARE USED IN THE WHOLE PROGRAM
JB_Cluster = {
Distance = 0,
PlayerPos = {x=0,y=0,world="void"},
SenderPos = {x=0,y=0,world="void"},
Prefix = "Void",
RQPrefix = "JBC_" ..  "Default", --UnitName("player").. tostring(random(1000)),
SongName = "Void",
PrintVar = false,
Chnum = "RAID", --GetChannelName("JukeboxCoin"),
ChanString = "void",
Indicator = ";",
Version = "0.1",
LocalPath = "Interface\\AddOns\\JukeboxCoin\\MyMusic\\",
}

local currently_playing = false


JBC_I_SHOULD_REALLY_NOT_DO_THIS = function() end

local JBCLib = LibStub:GetLibrary("JBClib")

local successfulRequest = C_ChatInfo.RegisterAddonMessagePrefix(JB_Cluster.RQPrefix)
--DEFINE FRAME RELATED TO EVENT HANDLING. I.E. THIS WILL HAVE ASSIGNED AT THE END OF THE CODE AN "ON EVENT" SCRIPT.
local RequestHandler = CreateFrame("FRAME", "ComHand")

--EXTRACTS POSITION FROM GAME
local function JBC_Position()
    local map = C_Map.GetBestMapForUnit("player")
    if (map) then
        local position = C_Map.GetPlayerMapPosition(map, "player")
        if (position) then
           return position:GetXY()
        else
	       return 0.0, 0.0
    end
    else
	     return 0.0, 0.0
    end
end
--CALCULATES DISTANCES
local function calc_distance(x1,y1,x2,y2,range)
return range*((x2-x1)^2+(y2-y1)^2)^0.5
end

---DEBUG FUNTION
local function printA()
	 if JB_Cluster.PrintVar == true then
	 print("|cFFFFFF00Message recived. Here is the data list:|r")
	 print("Player Position: " .. JB_Cluster.PlayerPos.x .. " " .. JB_Cluster.PlayerPos.y)
	 print("Sender Position: " .. JB_Cluster.SenderPos.x .. " " .. JB_Cluster.SenderPos.y)
	 print("Distance: " .. JB_Cluster.Distance)
	 print("Sender Prefix: " .. JB_Cluster.Prefix)
	 print("Player Prefix: " .. JB_Cluster.RQPrefix)
	 print("Sent string: " .. JB_Cluster.SongName)
	 print("String: " .. JB_Cluster.ChanString)
	 end
end 




local function Play_Music()
     JB_Cluster.PlayerPos.x, JB_Cluster.PlayerPos.y = JBC_Position()
	 JB_Cluster.Distance = calc_distance(JB_Cluster.PlayerPos.x,JB_Cluster.PlayerPos.y,JB_Cluster.SenderPos.x,JB_Cluster.SenderPos.y,100.0)
	 if JB_Cluster.Distance < 5  then 

       C_Timer.After(2, printA )
	 
       if JB_Cluster.SongName == "STOP" then
	    StopMusic()
       elseif JB_Cluster.SongName == "TEST" then
	     print("////***TEST SIGNAL ARRIVED***\\\\\\\\")
       else
          PlayMusic(JB_Cluster.SongName)
       end
     end	 

end


local function Jukebox_Sender_Prompt(text,duration,indicator)
		
	if JBCLib:CheckRaidCom() == true then
		if( UnitIsGroupLeader("player") or UnitIsGroupAssistant("player")) then

			JB_Cluster.PlayerPos.x, JB_Cluster.PlayerPos.y = JBC_Position()
			JB_Cluster.ChanString = text                   .. JB_Cluster.Indicator .. 
									JB_Cluster.PlayerPos.x .. JB_Cluster.Indicator ..
									JB_Cluster.PlayerPos.y 

			local success = C_ChatInfo.SendAddonMessage(JB_Cluster.RQPrefix, JB_Cluster.ChanString,JB_Cluster.Chnum)

			if success == false then
				JBCLib:EmptyQueue()
				JBC_I_SHOULD_REALLY_NOT_DO_THIS()
				--PlayMusic(text)
				print("|cFFFF0000     ERROR:|r  |cFF00FF00You need to be in a " .. JB_Cluster.Chnum .. " party.|r")
		    end
		else
			print("|cFFFF0000     ERROR:|r  |cFF00FF00You need to be raid leader or assistant.|r")
			JBCLib:EmptyQueue()
			JBC_I_SHOULD_REALLY_NOT_DO_THIS()
		end
	else
		PlayMusic(text)
	end




	if JB_Cluster.PrintVar == true then
	 print("|cFFFFFF00Here is the data list:|r")
	 print("Player Position: " .. JB_Cluster.PlayerPos.x .. " " .. JB_Cluster.PlayerPos.y)
	 print("Sender Prefix: " .. JB_Cluster.RQPrefix)
	 print("String: " .. JB_Cluster.ChanString)
	 end
   

end



function Queue_Reproduction()
    if JBCLib:CheckQueueLenght() > 0  then
		if JBCLib:CheckFlag() == true and JBCLib:ReturnPlayStatus() == true and currently_playing == false then
			currently_playing = true
			Jukebox_Sender_Prompt(JBCLib:ReturnID(1),JBCLib:ReturnDuration(1),JB_Cluster.Indicator);
			C_Timer.After(JBCLib:ReturnDuration(1), 
				function()
					currently_playing = false
					Queue_Reproduction();
				end)
			JBCLib:RemoveFromQueue(1); 
			JBC_I_SHOULD_REALLY_NOT_DO_THIS()

		elseif JBCLib:CheckFlag() == false then
			Jukebox_Sender_Prompt(JBCLib:ReturnID(1),JBCLib:ReturnDuration(1),JB_Cluster.Indicator);
			JBCLib:RemoveFromQueue(1);
			JBC_I_SHOULD_REALLY_NOT_DO_THIS()
			if JBCLib:CheckQueueLenght() > 0  then
				JBCLib:EmptyQueue()
			end

--		elseif currently_playing == true then
--			print("|cFF00FF00   There is already something playing.|r")
		end
      
    end

end


 function Submit_to_Reproduction(name,ID,duration)
		if JBCLib:CheckQueueLenght() > 0 or JBCLib:ReturnPlayStatus() == false then
			JBCLib:AddToQueue(name,ID,duration);
		elseif JBCLib:ReturnPlayStatus() == true then
			JBCLib:AddToQueue(name,ID,duration);
			Queue_Reproduction();
		end
end



function Abort_deny()
JB_MainFrame:Show();
end



local function eventHandler(self, event, prefix, text, channel, ...)

    if prefix == JB_Cluster.RQPrefix and channel == JB_Cluster.Chnum then
	  JB_Cluster.SongName, JB_Cluster.SenderPos.x, JB_Cluster.SenderPos.y = strsplit(JB_Cluster.Indicator, text)
      JB_Cluster.SenderPos.x = tonumber(JB_Cluster.SenderPos.x)
      JB_Cluster.SenderPos.y = tonumber(JB_Cluster.SenderPos.y)

      Play_Music()
      
      end
  end
  


   
   
   
local MH = function()
    print("USE SLASH COMMANDS")
	print("/MusicMenu will open the main menu")
	print ("/Mprefix to set a common prefix")
    print("/Mptr will open the prompt")
	print("/Mptr2 will open the prompt 2")
	print("STOP used in Mptr will stop the music")
	print("/MessPrint to show more informations in the comunication.")
  end


  

  




 
SLASH_MMHelp1 = "/MHelp"
SlashCmdList["MMHelp"] = function() 
MH()
end



RequestHandler:RegisterEvent("CHAT_MSG_ADDON")
RequestHandler:SetScript("OnEvent", eventHandler)


print("[|cFF00FF00JukeBox Coin|r-|cFFFF0000V " .. JB_Cluster.Version .. "|r] JukeBox Initialized");
print("[|cFF00FF00JukeBox Coin|r-|cFFFF0000V " .. JB_Cluster.Version .. "|r] Use slash command [MHelp] for help");









local saves = CreateFrame("FRAME"); -- Need a frame to respond to events
saves:RegisterEvent("ADDON_LOADED"); -- Fired when saved variables are loaded
saves:RegisterEvent("PLAYER_LOGOUT"); -- Fired when about to log out

function saves:OnEvent(event, arg1)
	if event == "ADDON_LOADED" and arg1 == "JukeboxCoin" then
		if JBC_PlaylistSaved == nil then
			JBCLib:Storelist(JBCLib:ReturnFirstPlaylist())
		else
			JBCLib:Storelist(JBC_PlaylistSaved)
		end
	elseif event == "PLAYER_LOGOUT" then
		JBC_PlaylistSaved = JBCLib:Returnlist()
	end
end



saves:SetScript("OnEvent", saves.OnEvent);




