-- Re-using my own code.
local activeSection = "Main"
local sectFocus = "Weight"

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

local panelWidth = _screen.w*0.3

local dirMaybe = "/Save/LocalProfiles/" .. profileID .. "/"

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

-- General navigation handling.
local function InputHandler( event )
	if event.GameButton == "Back" and event.type == "InputEventType_FirstPress" then
		SCREENMAN:PlayCancelSound()
		if activeSection == "Main" then
			ExitScreen()
		else
			activeSection = "Main"
			MESSAGEMAN:Broadcast("ActSectUpdated")
		end
	end
	
	if event.GameButton == "Start" and event.type == "InputEventType_FirstPress" then
		SCREENMAN:PlayStartSound()
		-- Gotta do this a bit weird to keep from two menus reacting at the same time.
		-- (activeSection doesn't change until whatever functions are called after this message's been sent)
		MESSAGEMAN:Broadcast("StartButton", {Sect=activeSection})
	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 t = Def.ActorFrame{
	OnCommand = function(self)
		SCREENMAN:GetTopScreen():AddInputCallback( InputHandler )
		--SM(LoadModule("Options.GetProfileData.lua")(profileID,true)["Image"])
	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()))
	-- },
	
	-- Manually the menu sound.
	LoadActor( THEME:GetPathS("Common","value") )..{
		NavigationMessageCommand=cmd(play)
	},
	
	-- ExplanationTogether lookalike.
	Def.BitmapText{
		Font="Common Normal",
		OnCommand=cmd(xy,_screen.cx,_screen.h-56;stoptweening;zoom,0.4;shadowlength,0;wrapwidthpixels,_screen.w/0.44;playcommand,"UpdateBlebText"),
		FocusUpdatedMessageCommand=cmd(playcommand,"UpdateBlebText"),
		UpdateBlebTextCommand=function(self)
			self:settext(THEME:GetString("ScreenOptionsCustomizeProfile", sectFocus .. "Explanation")):stoptweening():cropright(1):linear(0.5):cropright(0)
		end
	}
}

-- #################################################
-- Functions. Still not proud of how it's coded but here we go anyway.

local function DigitInputTime(theOption)
	-- Hard-coded(?) initial values.
	local initIal = {
		Weight = profile:GetWeightPounds(),
		Voomax = profile:GetVoomax(),
		BirthYear = profile:GetBirthYear()
	}
	
	local digitSettings = {
		SendOnPop = "",
		Question = THEME:GetString("ScreenOptionsCustomizeProfile", theOption .. "Entry"),
		InitialAnswer = initIal[theOption],
		MaxInputLength = 5,
		Password = false,
		Validate = function(answer, errorOut)
			if tonumber(answer) then return true, "" end
			return false, THEME:GetString("ScreenOptionsCustomizeProfile", "EntryNotANumber")
		end,	
		OnOK = function(answer)
			--SM(answer)
			
			if theOption == "Weight" then profile:SetWeightPounds(answer)
			elseif theOption == "Voomax" then profile:SetVoomax(answer)
			elseif theOption == "BirthYear" then profile:SetBirthYear(answer)
			end
			
			MESSAGEMAN:Broadcast("FocusUpdated")
		end,				-- On OK; function(answer)
		OnCancel = function() end,			-- On Cancel; function()
		ValidateAppend = nil,	-- Validate appending a character; function(answer,append), must return boolean
		FormatAnswerForDisplay = nil	-- Format answer for display; function(answer), must return string
	}
	
	SCREENMAN:AddNewScreenToTop("ScreenTextEntry")
	SCREENMAN:GetTopScreen():Load(digitSettings)
end

local function ProfileBooleanToggle(theOption, oldBool)
	if theOption == "CalCalc" then
		profile:SetIgnoreStepCountCalories(not oldBool)
	elseif theOption == "SexAlgorithm" then
		profile:SetIsMale(not oldBool)
	end
	
	MESSAGEMAN:Broadcast("FocusUpdated")
end

-- #################################################
-- Main menu.

local mainMenuChoices = {
	-- name, function to call when Start is pressed on this menu choice
	{"Weight", function() DigitInputTime("Weight") end},
	{"Voomax", function() DigitInputTime("Voomax") end},
	{"BirthYear", function() DigitInputTime("BirthYear") end},
	{"CalCalc", function() ProfileBooleanToggle("CalCalc", profile:GetIgnoreStepCountCalories()) end},
	{"SexAlgorithm", function() ProfileBooleanToggle("SexAlgorithm", profile:GetIsMale()) end},
	{"FoxAvatar", function()
			if #LoadModule("Profile.GetAvatarImageArray.lua")() > 0 then
				SCREENMAN:SetNewScreen("ScreenOptionsCustomizeProfileOutFoxAvatar")
			else
				SCREENMAN:PlayInvalidSound()
				SM("There are no images in the 'Appearance/Avatars' folder to choose from.")
			end
		end
	},
	{"Exit", function() ExitScreen() end}
}

local function MakeMainMenuItems()
	local t = {}
	
	for i, choic in ipairs(mainMenuChoices) do
		-- TODO: update style
		t[#t+1] = Def.ActorFrame{
			Def.BitmapText{
				Name="Title",
				Font="Common Normal",
				Text=string.upper(THEME:GetString("ScreenOptionsCustomizeProfile", choic[1])),
				OnCommand=function(self)
					self:uppercase(true):zoom(0.6):maxwidth(_screen.w/3.5):wrapwidthpixels((_screen.w/3.5)/0.6):
						horizalign(left):strokecolor(Color.Black):playcommand("UpdateBlebText")
				end,
				-- messy...
				FocusUpdatedMessageCommand=cmd(playcommand,"UpdateBlebText"),
				UpdateBlebTextCommand=function(self)
					self:diffuse(sectFocus == choic[1] and Color.White or ColorBlend(LocalBlueColor(1),Color.White))
				end
			},
			Def.BitmapText{
				Name="Value",
				Font="Common Normal",
				OnCommand=function(self)
					self:x((_screen.w/4)-16):zoom(0.6):maxwidth((_screen.w/3)/0.6):wrapwidthpixels((_screen.w/3)/0.6):
						horizalign(left):strokecolor(Color.Black):playcommand("UpdateBlebText")
				end,
				FocusUpdatedMessageCommand=cmd(playcommand,"UpdateBlebText"),
				-- messy...
				UpdateBlebTextCommand=function(self)
					local initIal = {
						Weight = profile:GetWeightPounds(),
						Voomax = profile:GetVoomax(),
						BirthYear = profile:GetBirthYear(),
						CalCalc = THEME:GetString("ScreenOptionsCustomizeProfile", "CalCalc_" .. tostring(profile:GetIgnoreStepCountCalories())),
						SexAlgorithm = THEME:GetString("ScreenOptionsCustomizeProfile", "SexAlgorithm_" .. tostring(profile:GetIsMale())),
						FoxAvatar = LoadModule("Config.Load.lua")( "AvatarImage", "/Save/LocalProfiles/"..profileID.."/OutFoxPrefs.ini" ),
						Exit = ""
					}
					self:diffuse(sectFocus == choic[1] and Color.White or ColorBlend(LocalGoldColor(1),Color.White))
					self:settext(initIal[choic[1]] or "...")
				end
			},
		}
	end
	
	return t
end

t[#t+1] = Def.ActorFrame {
	Name = 'Main',
	ActSectUpdatedMessageCommand=function(self)
		self:linear(0.01):diffusealpha(activeSection == "Main" and 1 or 0.5)
	end,
	Def.ActorScroller{
		Name = 'MainScroll',
		NumItemsToDraw=200,
		OnCommand=function(self)
			self:xy(20,_screen.cy/1.5):SetSecondsPerItem(0.01):SetFastCatchup(true)
		end,
		TransformFunction=function(self, offset, itemIndex, numItems)
			self:y(28*itemIndex)
		end,
		children = MakeMainMenuItems(),
		NavigationMessageCommand=function(self,params)
			if activeSection ~= "Main" then return end
			
			local numItemsInd = self:GetNumItems()-1
			-- floor it to prevent oddities caused by button mashing from occurring
			local location = math.floor(self:GetCurrentItem() + params.Movement)
			if location > numItemsInd then
				-- Don't go past the last item in the scroller.
				self:SetDestinationItem(0)
			elseif location < 0 then
				self:SetDestinationItem(numItemsInd)
			else
				self:SetDestinationItem(location)
			end
			
			-- Only one scroller on screen at a time, BUDDY!
			sectFocus = mainMenuChoices[self:GetDestinationItem()+1][1]
			MESSAGEMAN:Broadcast("FocusUpdated")
		end,
		StartButtonMessageCommand=function(self,params)
			if params.Sect ~= "Main" then return end
			mainMenuChoices[self:GetCurrentItem()+1][2]()
		end
	}
}

return t
