-- Profile stuff.
local profile = GAMESTATE:GetEditLocalProfile()
local profileID = GAMESTATE:GetEditLocalProfileID()

local outFoxDir = "Save/LocalProfiles/".. profileID .."/OutFoxPrefs.ini"
local foxAvs = LoadModule("Profile.GetAvatarImageArray.lua")()

-- #################################################
-- Functions.

local function ExitScreen()
	SCREENMAN:GetTopScreen():PostScreenMessage('SM_GoToNextScreen', 0)
end

local function InputHandler( event )
	if event.GameButton == "Back" and event.type == "InputEventType_FirstPress" then
		SCREENMAN:GetTopScreen():Cancel()
	end
	
	if event.GameButton == "Start" and event.type == "InputEventType_FirstPress" then
		SCREENMAN:PlayStartSound()
		MESSAGEMAN:Broadcast("StartButton")
	end
	
	if string.find(event.GameButton, "Menu") and event.type ~= "InputEventType_Release" then
		local mov = (event.GameButton == "MenuRight" or event.GameButton == "MenuDown") and 1 or -1
		local ver = (event.GameButton == "MenuUp" or event.GameButton == "MenuDown")
		MESSAGEMAN:Broadcast("Navigation", {Movement=mov, Vertical=ver})
	end
end

local rowItemCount = math.floor((_screen.w-((_screen.w/4)-30))/80)
local rowsBeforeScroll = 3

local function MakeAvatarMenuItems()
	local t = {}
	
	for i, av in ipairs(foxAvs) do
	-- av[1]: filename, av[2]: full path
		t[#t+1] = Def.ActorFrame{
			Def.Sprite{
				Texture=av[2],
				InitCommand=function(self)
					self:zoomto(64,64)
				end
			}
		}
	end
	
	return t
end

-- #################################################
-- Let's make our menu.

local t = Def.ActorFrame{
	OnCommand = function(self)
		SCREENMAN:GetTopScreen():AddInputCallback( InputHandler )
	end,
	
	-- Extra underlay thing.
	-- Def.Quad {
		-- InitCommand=cmd(horizalign,left;vertalign,bottom;y,_screen.h-(_screen.h/4.5);zoomto,_screen.w,(_screen.h/3);
			-- diffuse,ColorDarkTone(SecondaryThemeColor())),
		-- ColorChangedMessageCommand=cmd(decelerate,5;diffuse,ColorDarkTone(SecondaryThemeColor()))
	-- },
	
	Def.Sprite {
		OnCommand=function(self)
			local foxAv = LoadModule("Config.Load.lua")( "AvatarImage", "/Save/LocalProfiles/"..profileID.."/OutFoxPrefs.ini" )
			
			self:LoadBanner(foxAv or THEME:GetPathG("UserProfile", "generic icon"))
			self:xy(80,100):zoomto(96,96)
		end
	},
	
	LoadFont("Common Normal") .. {
		Text = "&DOWN;",
		OnCommand=function(self)
			self:xy(80,200)
		end
	},
	
	Def.Sprite {
		Name = "NewAv",
		OnCommand=function(self)
			-- Load up whatever the first avatar in the list is to start with.
			self:LoadBanner(foxAvs[1][2])
			self:xy(80,300):zoomto(96,96)
		end
	},
	
	-- Manually the menu sound.
	LoadActor( THEME:GetPathS("Common","value") )..{
		NavigationMessageCommand=cmd(play)
	},
		
	-- FOUR-WAY
	-- FREAKING
	-- SCROLLER
	-- TODO: fix navigation for cases where the number of avatars isn't even to the row length.
	-- ALSO TODO: keep from scrolling when it already is.
	Def.ActorScroller{
		NumItemsToDraw=200,
		OnCommand=function(self)
			self:xy((_screen.w/4)+20,_screen.cy/2.9):SetSecondsPerItem(0.01):SetFastCatchup(true)
		end,
		TransformFunction=function(self, offset, itemIndex, numItems)self:x((itemIndex % rowItemCount) * 80)
			self:y(math.floor(itemIndex / rowItemCount) * 80 )
			if math.abs(offset) < 1 then
				self:zoom(1.2)
			end
		end,
		children = MakeAvatarMenuItems(),
		NavigationMessageCommand=function(self,params)
			local verMult = params.Vertical and rowItemCount or 1
			local dist = params.Movement * verMult
			local location = math.floor(self:GetCurrentItem() + dist)
			-- STAY IN BOUNDS! We have to do this manually to handle vertical movement.
			if location > self:GetNumItems()-1 then
				-- Don't go past the last item in the scroller.
				-- feat. fiddly maths for vertical movement
				location = verMult == 1 and 0 or 0 + (self:GetCurrentItem() % rowItemCount)
			elseif location < 0 then
				-- Don't scroll backwards into oblivion, either.
				location = verMult == 1 and self:GetNumItems()-1 or self:GetNumItems()-rowItemCount + (self:GetCurrentItem() % rowItemCount)
			end
			
			self:SetDestinationItem(location)
			-- Update the avatar preview.
			local newAv = self:GetParent():GetChild("NewAv")
			newAv:LoadBanner(foxAvs[location + 1][2])
			newAv:zoomto(96,96)
			
			-- TODO: make way cleaner.
			if (location+1) > (rowItemCount * rowsBeforeScroll) then
				self:stoptweening():linear(0.5):y(_screen.cy/2.9 - ( 80 * ( math.floor(location / rowItemCount) - rowsBeforeScroll ) ))
			else
				self:stoptweening():linear(0.5):y(_screen.cy/2.9)
			end
			
			--SM(self:GetCurrentItem()+1)
		end,
		StartButtonMessageCommand=function(self,params)
			-- let's get outta here
			LoadModule("Config.Save.lua")( "AvatarImage", foxAvs[self:GetCurrentItem()+1][2], outFoxDir )
			ExitScreen()
		end
	}
}

return t

