-- do not touch anything below or I will cry ~Wiz --


local nowplaying = ""

local requests = {
}

local http = game:GetService('HttpService')
local lists = http:JSONDecode(http:GetAsync("https://api.trello.com/1/boards/"..trelloboard.."/lists"))
for _,v in pairs(lists) do
	if v.name == "Indie" then
		local items = http:JSONDecode(http:GetAsync("https://api.trello.com/1/lists/"..v.id.."/cards"))
		print(#items)
		for _,v in pairs(items) do
			if v.name:match(":") ~= nil then
				local s,f = string.find(v.name,":")
				table.insert(songs, string.sub(v.name,f+1))	
			end
		end
	end
end

function shuffleTable(t)
	math.randomseed(tick())
	assert(t, "shuffleTable() expected a table, got nil" )
	local iterations = #t
	local j
	for i = iterations, 2, -1 do
		j = math.random(i)
		t[i], t[j] = t[j], t[i]
	end
end

shuffleTable(songs)

local songnum = 0

function script.Parent.musicEvents.getSong.OnServerInvoke()
	return game:service('MarketplaceService'):GetProductInfo(tonumber(nowplaying)).Name
end

script.Parent.musicEvents.purchaseSong.OnServerEvent:connect(function(p)
	if p.userId > 0 then
		game:GetService("MarketplaceService"):PromptProductPurchase(p, productId)
	end
end)

local votes = {
	
}

function makesong()
	script.Parent.Parent.Parent.Body.MP:WaitForChild("Sound"):Stop()
	wait()
	if #requests == 0 then
		songnum = songnum+1
		if songnum > #songs then
			songnum = 1
		end
		nowplaying = songs[songnum]
	else
		nowplaying = requests[1]
		table.remove(requests,1)
	end
	local thisfunctionssong = nowplaying
	script.Parent.Parent.Parent.Body.MP.Sound.SoundId = "rbxassetid://"..thisfunctionssong
	wait()
	script.Parent.Parent.Parent.Body.MP.Sound:Play()
	script.Parent.musicEvents.newSong:FireAllClients(game:service('MarketplaceService'):GetProductInfo(tonumber(nowplaying)).Name)
	votes = {}
	wait(script.Parent.Parent.Parent.Body.MP.Sound.TimeLength)
	if "rbxassetid://"..nowplaying == "rbxassetid://"..thisfunctionssong then
		makesong()
	end
end

function countVotes()
	local c = 0
	for _,v in pairs(votes) do
		if v[2] == true then
			c = c +1
		end
	end
	local remainder = #game.Players:GetPlayers() - #votes
	local percent = (c + (remainder/2))/#game.Players:GetPlayers()
	script.Parent.musicEvents.voteChange:FireAllClients(percent)
	if percent <= 0.2 then
		--skip song
		makesong()
	end
	return
end

script.Parent.musicEvents.voteYes.OnServerEvent:connect(function(p)
	for _,v in pairs(votes) do
		if v[1] == p.Name then
			v[2] = true
			countVotes()
			return
		end
	end
	table.insert(votes, {p.Name, true})
	countVotes()
end)

script.Parent.musicEvents.voteNo.OnServerEvent:connect(function(p)
	for _,v in pairs(votes) do
		if v[1] == p.Name then
			v[2] = false
			countVotes()
			return
		end
	end
	table.insert(votes, {p.Name, false})
	countVotes()
end)
