local vidPlaying = false
local musicStart = false
local musicDelay = 0

local function PreviewVidDelayHandling(self, deltaTime)
	local theWheel = SCREENMAN:GetTopScreen():GetMusicWheel()
	
	-- logic for the variables to control playing the thing, and for WheelMovingIndicator
	if theWheel:IsSettled() then
		self:GetChild("WheelMovingIndicator"):visible(false)
		if not SOUND:IsTimingDelayed() and not musicStart then
			musicStart = true
		end
	else
		self:GetChild("WheelMovingIndicator"):visible(true)
		musicStart = false
		vidPlaying = false
	end
	
	-- logic for actually playing the thing, and the static that obfuscates the display when the music sample hasn't started
	if musicStart and not vidPlaying then
		vidPlaying = true
		-- Now with shaky handling for rate mods; might cause the preview to fall out of sync sooner
		self:GetChild("PreviewThing"):play():rate(GAMESTATE:GetSongOptionsObject("ModsLevel_Preferred"):MusicRate())
		self:GetChild("WorkingNoise"):visible(false)
	elseif not musicStart then
		self:GetChild("PreviewThing"):pause()
		self:GetChild("WorkingNoise"):visible(true)
	end
end

local t = Def.ActorFrame{
	InitCommand=function(self)
		self:Center()
	end,
	
	-- ActorFrame containing preview stuff.
	Def.ActorFrame{
		InitCommand=function(self)
			self:SetUpdateFunction(PreviewVidDelayHandling):y(-20)
		end,
		
		-- Frame behind the previewvid display...
		Def.Quad {
			OnCommand=function(self)
				self:diffuse(Color.Black):zoomto(240,135)
			end
		},
		
		-- ...and the previewvid display!
		Def.Sprite {
			Name = "PreviewThing",
			InitCommand=function(self)
				self:pause()
			end,
			SetCommand=function(self,param)
				local songOrCourse = GAMESTATE:IsCourseMode() and GAMESTATE:GetCurrentCourse() or GAMESTATE:GetCurrentSong()
				if songOrCourse and not GAMESTATE:IsCourseMode() then --thonk
					self:LoadBanner(songOrCourse:GetPreviewVidOrBGPath())
					self:aux(1)
				else
					self:aux(0)
					-- Get a bit iffy for the sake of showing those pretty group jackets
					-- TODO: how handle sort menu?
					local mWheel = SCREENMAN:GetTopScreen():GetChild("MusicWheel")
					local sortOrder = GAMESTATE:GetSortOrder()
					local wheelText = mWheel:GetSelectedSection()
					local wheelType = ToEnumShortString(mWheel:GetSelectedType())
					
					if sortOrder == "SortOrder_Group" and SONGMAN:DoesSongGroupExist(wheelText) and GetSongGroupJacketOrBanner(wheelText,true) then
						self:LoadBanner(GetSongGroupJacketOrBanner(wheelText,true))
					elseif sortOrder == "SortOrder_Preferred" then
						self:LoadBanner(THEME:GetPathG("","_PrefSort/Banner/" .. wheelText))
					else
						self:LoadBanner(THEME:GetPathG("Common","fallback background"))
					end
				end
				
				self:scaletofit(-120,-67.5,120,67.5):position(0):playcommand("CheckMirror")
			end,
			
			CurrentSongChangedMessageCommand=cmd(playcommand,"Set"),
			CurrentCourseChangedMessageCommand=cmd(playcommand,"Set"),
			
			CheckSongRateCommand=function(self)
				self:rate(GAMESTATE:GetSongOptionsObject("ModsLevel_Preferred"):MusicRate())
			end,
			CheckMirrorCommand=function(self)
				self:rotationy((CheckShouldMirrorBG(true) and self:getaux() == 1) and 180 or 0)
			end,
			-- help it notice if the rate mod (and also the mirroring) might have been changed through OptionsList
			OptionsListStartMessageCommand=cmd(playcommand,"CheckSongRate";playcommand,"CheckMirror"),
			OptionsListResetMessageCommand=cmd(playcommand,"CheckSongRate";playcommand,"CheckMirror"),
		},
		
		-- Overlay for when the song preview hasn't started yet.
		LoadActor(THEME:GetPathB("ScreenNoise","background"), 240, 135) .. {
			Name = "WorkingNoise",
			OnCommand=function(self)
				self:diffusealpha(0.5)
			end
		},
		
		-- Backing behind the para dance info.
		Def.Quad {
			Name = "TextBacking",
			InitCommand=function(self)
				self:diffuse(LocalGoldColor(0.5)):vertalign(bottom):y(67.5):zoomto(240,0):blend(Blend.Modulate)
			end
		},
		
		-- The info for teh para danec (if available).
		Def.BitmapText{
			Name = "pmtxt",
			Condition = not GAMESTATE:IsCourseMode() and GAMESTATE:GetCurrentGame():GetName() == "para",
			Font = "Common Normal",
			InitCommand=function(self)
				self:horizalign(left):vertalign(bottom):xy(-116,62):zoom(0.3):strokecolor(Color.Black):maxwidth(228/0.3):wrapwidthpixels(228/0.3)
			end,
			SetCommand=function(self)
				local backing = self:GetParent():GetChild("TextBacking")
				local target = GAMESTATE:GetCurrentSong()
				if target then
					if target:IsFreestyleOnly() then
						self:settext(THEME:GetString("ScreenSelectMusic","FreestyleOnly"))
					else
						local paraData = target:GetParamaniaIni()
						self:settext(THEME:GetString("Misc", "MdDancer") .. ": " .. paraData.Metadata.Dancers .. "\n" .. THEME:GetString("Misc", "MdChoreoS") .. ": " .. paraData.Metadata.Choreo)
					end
					backing:visible(true):zoomy((self:GetHeight() * 0.3) + 8)
				else
					self:settext("")
					backing:visible(false)
				end
			end,
			CurrentSongChangedMessageCommand=cmd(playcommand,"Set")
		},
		
		-- Overlay for when the wheel hasn't stopped on a song yet.
		Def.ActorFrame {
			Name = "WheelMovingIndicator",
			
			Def.Quad {
				OnCommand=function(self)
					self:diffuse(Color.Alpha(LocalGoldColor(1),0.6)):zoomto(240,135)
				end
			},
			Def.BitmapText {
				Font = "Common Normal",
				Text = THEME:GetString("ScreenSelectMusic", "WheelMoving"),
				OnCommand=function(self)
					self:xy(110,57):zoom(0.4):horizalign(right):strokecolor(LocalGoldColor(0))
				end
			}
		},
		
		-- Here's a glowy frame.
		LoadActor("vidframe") .. {
			OnCommand=function(self)
				self:zoom(1):blend(Blend.Add)
			end
		},
		
		-- Bouncing menu buttons!
		Def.BitmapText {
			Font = "Common Normal",
			Text = "&MENULEFT;",
			OnCommand=function(self)
				self:x(-144):zoom(0.75):bounce():effectmagnitude(4,0,0):effectperiod(1):effectclock("bgm")
			end
		},
		Def.BitmapText {
			Font = "Common Normal",
			Text = "&MENURIGHT;",
			OnCommand=function(self)
				self:x(144):zoom(0.75):bounce():effectmagnitude(-4,0,0):effectperiod(1):effectclock("bgm")
			end
		},
		
		-- An indicator for when VidMirror or w/e is on.
		-- TODO: make indicator work for "arcade" and "static" modes.
		Def.BitmapText{
			Font = "Common Normal",
			Text = "<PERFORMANCE>",
			OnCommand=function(self)
				self:horizalign(right):vertalign(top):xy(120,-66):zoom(0.4):strokecolor(Color.Black):maxwidth(240/0.3):wrapwidthpixels(240/0.3):playcommand("CheckMirror")
			end,
			CheckMirrorCommand=function(self)
				self:visible(CheckShouldMirrorBG(true))
			end,
			-- help it notice if the mirroring might have been changed through OptionsList
			OptionsListStartMessageCommand=cmd(playcommand,"CheckMirror"),
			-- ack
			CurrentSongChangedMessageCommand=cmd(playcommand,"CheckMirror"),
			CurrentCourseChangedMessageCommand=cmd(playcommand,"CheckMirror"),
		}
	},
}

if GAMESTATE:IsCourseMode() then
	-- Oh janky course contents list, how I tolerate you so
	t[#t+1] = LoadActor("CourseContentsList") .. {
		InitCommand=function(self)
			self:y(162)
		end
	}
else
	-- Man, we're only now getting to the StepsDisplay?!
	t[#t+1] = LoadActor("StepsDisplay") .. {
		InitCommand=function(self)
			self:y(128)
		end
	}
end


t[#t+1] = LoadActor("PlayerMenu", PLAYER_1)
t[#t+1] = LoadActor("PlayerMenu", PLAYER_2)

t[#t+1] = LoadActor("BublLeft") .. {
	InitCommand=function(self)
		self:xy(-_screen.w/3,-_screen.h/3):bob():effectmagnitude(0,1,0)
	end
}

return t
