------------------------------------
-- I'VE NO CLUE OF WHAT THESE ARE --
------------------------------------

local _, core = ... ;
core.Config = {};
local Config = core.Config;

local LibRPMedia = LibStub:GetLibrary("LibRPMedia-1.0");
local JBCLib = LibStub:GetLibrary("JBClib")

local StdUi = LibStub('StdUi');

local Main_frame = StdUi:Window(UIParent, 250, 400, 'JukeboxCoin Menu');






---------------------------------
----  QUEUE MENU  -------
---------------------------------

--Variable to load the max lenght of music
local QueueList = JBCLib:CheckQueueLenght()
---Sets the main frame
local QueueList_ScrollFrame = StdUi:Window(UIParent, 350,230, 'Queue List');
QueueList_ScrollFrame:SetPoint('CENTER', 0,400);
--creating back button
local QueueList_Button = StdUi:Button(QueueList_ScrollFrame, 100, 20, 'Back');
StdUi:GlueTop(QueueList_Button, QueueList_ScrollFrame, 0, -200, 'CENTER');
QueueList_Button:SetScript('OnClick', function()	QueueList_ScrollFrame:Hide(); Main_frame:Show();   end)
-- Generate data list
local data_q = {};
for i = 1, QueueList do
	tinsert(data_q, {text = JBCLib:ReturnName(i),
				   ID = JBCLib:ReturnID(i),
				   duration = JBCLib:ReturnDuration(i),
				   index = i,
				   });
end
-- Draw hybrid scroll frame
local hsf_q = StdUi:HybridScrollFrame(QueueList_ScrollFrame, 330,160);
hsf_q:SetScrollStep(10);
hsf_q:SetPoint('CENTER');
hsf_q:SetDoNotHideScrollBar(true);


local function Queue_upper()
			QueueList = JBCLib:CheckQueueLenght()
            data_q = {};
            for i = 1, QueueList do
	            tinsert(data_q, {text = JBCLib:ReturnName(i),
	 			   ID = JBCLib:ReturnID(i),
				   duration = JBCLib:ReturnDuration(i),
				   index = i,
				   });
end
end

local create_q = function(parent)
	local btn = StdUi:Button(parent, 200, 20, 'Z');
	return btn;
end


local update_q = function(parent, itemFrame, d)
	itemFrame.data = d;
	itemFrame:SetText(d.text);
    itemFrame:SetScript("OnClick",
		function(self, button, down)

            JBCLib:RemoveFromQueue(itemFrame.data.index);
			JBC_I_SHOULD_REALLY_NOT_DO_THIS()
		end )
end;

-- You can create any type of widget here or just pass 'Button' instead,
-- Any StdUi simple widget should work

---Creates first default list of buttons.
hsf_q:CreateItems(data_q, create_q, update_q, 1);
QueueList_ScrollFrame:Hide()


JBC_I_SHOULD_REALLY_NOT_DO_THIS = function()
Queue_upper()
hsf_q:CreateItems(data_q, create_q, update_q, 1);

end





---------------------------------
----  FIRST SCROLL MENU  --------
---------------------------------



--Variable to load the max lenght of music and other jam
local MusicSize = Jukebox_Coin_Music_Size();
local nameMus = JukeboxCoin_Get_Music_List();
local durMus = JukeboxCoin_Get_Music_List_Duration()
---Sets the main frame
local CuscomMusic_ScrollFrame = StdUi:Window(UIParent, 650,450, 'Game Music List');
CuscomMusic_ScrollFrame:SetPoint('CENTER', -550,0);
--creating back button
local CustomMusicBack_Button = StdUi:Button(CuscomMusic_ScrollFrame, 200, 30, 'Back');
StdUi:GlueTop(CustomMusicBack_Button, CuscomMusic_ScrollFrame, 200, -400, 'CENTER');
CustomMusicBack_Button:SetScript('OnClick', function()	CuscomMusic_ScrollFrame:Hide(); Main_frame:Show();     end)
-- Generate data list
local data_c = {};
for i = 1, MusicSize do
	tinsert(data_c, {text = nameMus[i],
				   ID = nameMus[i],
				   duration = durMus[i],
				   });
end


-- Draw hybrid scroll frame
local hsf_c = StdUi:HybridScrollFrame(CuscomMusic_ScrollFrame, 600,310);
hsf_c:SetScrollStep(10);
hsf_c:SetPoint('CENTER');
hsf_c:SetDoNotHideScrollBar(true);

-- Update function for buttons props
local update_c = function(parent, itemFrame, d)
	itemFrame.data = d;
	itemFrame:SetText(d.text);
	itemFrame:RegisterForClicks("AnyUp");
--	local stopmusic_text = "Left Click: |cffffffff Play for everyone (goes in queue)|r\n" ..
--	                       "Right Click: |cffffffff Play only for you" 
--    itemFrame.tooltip = StdUi:FrameTooltip(itemFrame, stopmusic_text, 'simp_tooltip2', "TOPRIGHT", true);
    itemFrame:SetScript("OnClick",
		function(self, button, down)

			if button == "LeftButton" then	
					Submit_to_Reproduction(itemFrame.data.text,
				                       JB_Cluster.LocalPath .. itemFrame.data.ID ..".mp3" ,
									   itemFrame.data.duration )
					print( "        |cFF00FF00"  ..  itemFrame.data.text .. "|r");
					Queue_upper()
					hsf_q:CreateItems(data_q, create_q, update_q, 1);
			else
				PlayMusic(JB_Cluster.LocalPath .. itemFrame.data.ID ..".mp3" );
				print("        |cFF00FF00" .. JB_Cluster.LocalPath .. itemFrame.data.ID .. ".mp3" .. "|r");
			end
		end )
end;

-- You can create any type of widget here or just pass 'Button' instead,
-- Any StdUi simple widget should work
local create_c = function(parent)
	local btn = StdUi:Button(parent, 400, 30, 'Z');
	return btn;
end
---Creates first default list of buttons.
hsf_c:CreateItems(data_c, create_c, update_c, 1);
CuscomMusic_ScrollFrame:Hide() --hides the frame
---Search bar props




---------------------------------
----  SECOND SCROLL MENU  -------
---------------------------------

--Variable to load the max lenght of music
local MusicSizeII = LibRPMedia:GetNumMusicFiles();
---Sets the main frame
local GameMusic_ScrollFrame = StdUi:Window(UIParent, 650,450, 'Game Music List');
GameMusic_ScrollFrame:SetPoint('CENTER', 550,0);
--creating back button
local GameMusicBack_Button = StdUi:Button(GameMusic_ScrollFrame, 200, 30, 'Back');
StdUi:GlueTop(GameMusicBack_Button, GameMusic_ScrollFrame, 200, -400, 'CENTER');
GameMusicBack_Button:SetScript('OnClick', function()	GameMusic_ScrollFrame:Hide(); Main_frame:Show();     end)
-- Generate data list
local data = {};
for i = 1, MusicSizeII do
	tinsert(data, {text = LibRPMedia:GetMusicNameByIndex(i),
				   ID = LibRPMedia:GetMusicFileByIndex(i),
				   });
end
-- Draw hybrid scroll frame
local hsf = StdUi:HybridScrollFrame(GameMusic_ScrollFrame, 600,310);
hsf:SetScrollStep(10);
hsf:SetPoint('CENTER');
hsf:SetDoNotHideScrollBar(true);

-- Update function for buttons props
local update = function(parent, itemFrame, d)
	itemFrame.data = d;
	itemFrame:SetText(d.text);
	itemFrame:RegisterForClicks("AnyUp");
--	local stopmusic_text = "Left Click: |cffffffff Play for everyone (goes in queue)|r\n" ..
--	                       "Right Click: |cffffffff Play only for you" 
--    itemFrame.tooltip = StdUi:FrameTooltip(itemFrame, stopmusic_text, 'simp_tooltip2', "TOPRIGHT", true);
    itemFrame:SetScript("OnClick",
		function(self, button, down)

			if button == "LeftButton" then	

				Submit_to_Reproduction(itemFrame.data.text,
				                       itemFrame.data.ID,
									   LibRPMedia:GetMusicFileDuration(itemFrame.data.ID) )
				print( "        |cFF00FF00"  .. itemFrame.data.text .. "|r");
				Queue_upper()
			    hsf_q:CreateItems(data_q, create_q, update_q, 1);
			else
				PlayMusic(itemFrame.data.ID);
				print("        |cFF00FF00"  .. itemFrame.data.text .. " - " .. itemFrame.data.ID .. "|r");
			end
		end )
end;

-- You can create any type of widget here or just pass 'Button' instead,
-- Any StdUi simple widget should work
local create = function(parent)
	local btn = StdUi:Button(parent, 400, 30, 'Z');
	return btn;
end
---Creates first default list of buttons.
hsf:CreateItems(data, create, update, 1);
GameMusic_ScrollFrame:Hide() --hides the frame
---Search bar props
local Game_Search_Box = StdUi:SearchEditBox(GameMusic_ScrollFrame, 350, 40, 'Search');
StdUi:GlueBelow(Game_Search_Box, GameMusic_ScrollFrame, -120, 55, 'CENTER');   
Game_Search_Box:SetScript("OnChar", function(self)   --
  data = {}
  for index, file, name in LibRPMedia:FindMusicFiles(self:GetText(),{ method = "substring" }) do
  tinsert(data, {text = name,
				   ID = file,
				   });
  end
 hsf:CreateItems(data, create, update, 1);
 end)
Game_Search_Box:HookScript("OnEnterPressed" ,
                            function(self)
  data = {}
  for index, file, name in LibRPMedia:FindMusicFiles(self:GetText(),{ method = "substring" }) do
  tinsert(data, {text = name,
				   ID = file,
				   });
  end
 hsf:CreateItems(data, create, update, 1);
							end)

   
 


















-------------------------
------- MAIN FRAME ------
------------------------- 

----Main Item
--local Main_frame = StdUi:Window(UIParent, 250, 400, 'Jukebox Coin');
Main_frame:SetPoint('CENTER', 0, 0);

----Prefix Items
-----------------------------------
local Prefix_Button = StdUi:Button(Main_frame, 200, 30, 'Change Prefix');
StdUi:GlueTop(Prefix_Button, Main_frame, 0, -50, 'CENTER')
Prefix_Button:SetScript('OnClick', function() Main_frame:Hide(); StaticPopup_Show("MUSIC_PREFIX"); end)
local pref_text = "Changes Music Prefix:\n" ..
            "|cffffffffMusic can be heard only by players\n"..
			"with the same prefix, even\n"..
			"if in the same raid.|r"
local Pref_Tooltip = StdUi:FrameTooltip(Prefix_Button, pref_text, 'simp_tooltip2', "TOPRIGHT", true);

----Game Music Items
-----------------------------------
local GameMusic_Button = StdUi:Button(Main_frame, 200, 30, 'Game Music');
StdUi:GlueTop(GameMusic_Button, Main_frame, 0, -100, 'CENTER');
GameMusic_Button:SetScript('OnClick', function()GameMusic_ScrollFrame:Show(); end)
local gamemusic_text = "Open Game Menu Music:\n" ..
            "|cffffffffHere you will find the list\n"..
			"with all the game musics."
local GameMusic_Tooltip = StdUi:FrameTooltip(GameMusic_Button, gamemusic_text, 'simp_tooltip2', "TOPRIGHT", true);

----Game Music Manual Items
-----------------------------------
local GameMusicManual_Button = StdUi:Button(Main_frame, 200, 30, 'Manual');
StdUi:GlueTop(GameMusicManual_Button, Main_frame, 0, -140, 'CENTER');
GameMusicManual_Button:SetScript('OnClick', function()	StaticPopup_Show("MUSIC_PROMPT2"); end)
local gamemusicmanual_text = "Open Manual Menu:\n" ..
            "|cffffffffHere you will be able to hand type\n" ..
            "the ID of the ingame music files."
local GameMusicManual_Tooltip = StdUi:FrameTooltip(GameMusicManual_Button, gamemusicmanual_text, 'simp_tooltip2', "TOPRIGHT", true);

----Custom Music Items
-----------------------------------
local CustomMusic_Button = StdUi:Button(Main_frame, 200, 30, 'Custom Music');
StdUi:GlueTop(CustomMusic_Button, Main_frame, 0, -180, 'CENTER');
CustomMusic_Button:SetScript('OnClick', function() CuscomMusic_ScrollFrame:Show(); end)
local custommusic_text = "Open Custom Menu Music:\n" ..
            "|cffffffffHere you will find the list\n"..
			"with some custom sound files."
local CustomMusic_Tooltip = StdUi:FrameTooltip(CustomMusic_Button, custommusic_text, 'simp_tooltip2', "TOPRIGHT", true);

----StopMusic Items
-----------------------------------
local StopMusic_Button = StdUi:Button(Main_frame, 200, 30, 'Stop Music');
StdUi:GlueTop(StopMusic_Button, Main_frame, 0, -220, 'CENTER');
StopMusic_Button:SetScript('OnClick', function() StopMusic(); end)
local stopmusic_text = "Stop Music:\n" ..
            "|cffffffffStops the currently playing music"
local StopMusic_Tooltip = StdUi:FrameTooltip(StopMusic_Button, stopmusic_text, 'simp_tooltip2', "TOPRIGHT", true);

----ShowQueue Items
-----------------------------------
local ShowQueue_Button = StdUi:Button(Main_frame, 200, 30, 'Show Queue');
StdUi:GlueTop(ShowQueue_Button, Main_frame, 0, -310, 'CENTER');
ShowQueue_Button:SetScript('OnClick', function() Queue_upper(); hsf_q:CreateItems(data_q, create_q, update_q, 1); QueueList_ScrollFrame:Show(); end)
local showqueue_text = "Show Queue:\n" ..
            "|cffffffffWill show the current queue."
local StopMusic_Tooltip = StdUi:FrameTooltip(ShowQueue_Button, showqueue_text, 'simp_tooltip2', "TOPRIGHT", true);



---Toggle Queue Items
-----------------------------------
local ToggleQueue_Button = StdUi:Button(Main_frame, 140, 30, 'Toggle Queue (On)');
StdUi:GlueTop(ToggleQueue_Button, Main_frame, 30, -350, 'CENTER');
ToggleQueue_Button:SetScript('OnClick',
              function(self)
			     if JBCLib:ToggleQueue() == true then
                 StdUi:ButtonLabel(ToggleQueue_Button, "Toggle Queue (On)");
				 StdUi:MarkAsValid(self, true)
				 else
				 StdUi:ButtonLabel(ToggleQueue_Button, "Toggle Queue (Off)");
				 StdUi:MarkAsValid(self, false)
				 Queue_upper(); hsf_q:CreateItems(data_q, create_q, update_q, 1);
				 end;
				  end)
local togglequeue_text = "Turn Queue System On/Off:\n" ..
            "|cffffffffThe reprodiction of the music can be\n"..
            "on queue or instantaneous. if queue is off\nit will delete the current queue.\n"
local ToggleQueue_Tooltip = StdUi:FrameTooltip(ToggleQueue_Button, togglequeue_text, 'simp_tooltip2', "TOPRIGHT", true);

---Bump Items
-----------------------------------
local Bump_Button = StdUi:Button(Main_frame, 50, 30, 'Pause');
StdUi:GlueTop(Bump_Button, Main_frame, -75, -350, 'CENTER');
Bump_Button:SetScript('OnClick',
              function()
              JBCLib:PlayPause()
			  if JBCLib:ReturnPlayStatus() == true then
              StdUi:ButtonLabel(Bump_Button, "Pause");			  
			  Queue_Reproduction(); 
			  elseif JBCLib:ReturnPlayStatus() == false then
              StdUi:ButtonLabel(Bump_Button, "Play");	
			  end
			  end)

Main_frame:Hide()














StaticPopupDialogs["MUSIC_PREFIX"] = {
    text = "Current Prefix: " .. JB_Cluster.RQPrefix .. " Insert the new Prefix",
    button1 = "Proceed",
    button2 = "Abort",
    hasEditBox = true,
    OnAccept = function (self, data, data2)
	JB_Cluster.RQPrefix = "JBC_" .. self.editBox:GetText();
	local successfulRequest = C_ChatInfo.RegisterAddonMessagePrefix(JB_Cluster.RQPrefix)
	StaticPopupDialogs["MUSIC_PREFIX"].text = "Current Prefix: " .. JB_Cluster.RQPrefix .. " Insert the new Prefix";
	 Main_frame:Show();
	if JB_Cluster.PrintVar == true then
	print("Prefix set to: " .. JB_Cluster.RQPrefix);
	end
    end,
	OnCancel = function (_,reason)
             Main_frame:Show();
           end,
    timeout = 0,
    whileDead = true,
    hideOnEscape = true,
    preferredIndex = 3,
}



StaticPopupDialogs["MUSIC_PROMPT2"] = {
    text = "Insert the name of the music file.",
    button1 = "Proceed",
    button2 = "Abort",
    hasEditBox = true,
    OnAccept =  function(self, data, data2)
	  if self.editBox:GetText() ~= "STOP" then
	  duration = LibRPMedia:GetMusicFileDuration(tonumber(self.editBox:GetText()))
	  name = LibRPMedia:GetMusicNameByFile(tonumber(self.editBox:GetText()))
      Submit_to_Reproduction(name,self.editBox:GetText(),duration)
	  JBC_I_SHOULD_REALLY_NOT_DO_THIS()
	  Main_frame:Show();
	  else
	  Submit_to_Reproduction("STOP","STOP",10);
	  end
	 end,
	OnCancel = function (_,reason)
               Main_frame:Show();
    end,
    timeout = 0,
    whileDead = true,
    hideOnEscape = true,
    preferredIndex = 3,
}
   

   local LDB = LibStub("LibDataBroker-1.1", true)
    local LDBIcon = LDB and LibStub("LibDBIcon-1.0", true)
    if LDB then
        local JBC_MinimapBtn = LDB:NewDataObject("MainButton", {
            type = "launcher",
			text = "JukeboxAddon",
            icon = "Interface/ICONS/INV_Trinket_80_Kultiras02c.blp",
            OnClick = function(_, button)
                if button == "LeftButton" then Main_frame:Show() end
            end,
            OnTooltipShow = function(tt)
                tt:AddLine("JukeboxCoin")
                tt:AddLine("|cffffff00Click|r Open JukeboxCoin main menu.")
            end,
        })
        if LDBIcon then
           LDBIcon:Register("MainButton", JBC_MinimapBtn, JBC_MinimapPos)
        end
    end



