-- TODO: character screen cancel button; tasks


-- Menu

function OpenMenu()
	GetPlayer():DoTaskInTime(0, ToggleMenu)
end

-- Spawning

local wormholeOne = nil
local wormholeTwo = nil

local function WormholeManager(inst)
	if not wormholeOne then			
		wormholeOne = inst
		
		print("Spawn another wormhole to complete the link.")
	elseif not wormholeTwo then
		wormholeTwo = inst
		
		wormholeOne.components.teleporter:Target(wormholeTwo)
		wormholeTwo.components.teleporter:Target(wormholeOne)
		
		wormholeOne = nil
		wormholeTwo = nil
		
		print("Wormholes linked.")
	end
end

function Spawn(prefab, count)
	if not prefab then
		print("Invalid prefab. Did you forget to activate the spawn menu?")
		return
	end
	
	local inst = SpawnPrefab(prefab)
	
	if inst then
		if prefab == "smallbird" then
			inst.sg:GoToState("hatch")
		elseif prefab == "mandrake" then
			if GetClock():IsDay() then
				inst.sg:GoToState("death")
			else
				inst.userfunctions.MakeFollower(inst)
				inst.sg:GoToState("idle")
			end
		elseif prefab == "teenbird" then
			inst.userfunctions.FollowPlayer(inst)
		elseif prefab == "wormhole" or prefab == "wormhole_limited_1" then
			WormholeManager(inst)
		end	
		
		inst.Transform:SetPosition(TheInput:GetMouseWorldPos():Get())
		
		if count and count > 1 then return Spawn(prefab, count - 1) end
	end
end

function SpawnInv(prefab, count)
	if not prefab then
		print("Invalid prefab. Did you forget to activate the spawn menu?")
		return
	end
	
	local inst = GetPlayer()
	local prefabInst = SpawnPrefab(prefab)
	
	if inst and prefabInst then
		inst.components.inventory:GiveItem(prefabInst)
		
		if count and count > 1 then return SpawnInv(prefab, count - 1) end
	end
end

-- Toggles

function ToggleGodMode()
	local inst = GetPlayer()
	
	if inst then 
		if inst.components.health:IsInvincible() then
			inst.components.health:SetInvincible(false)
			print("God mode disabled.")
		else
			inst.components.health:SetInvincible(true)
			print("God mode enabled.")
		end
	end
end

function ToggleRain()
	local seasonManager = GetSeasonManager()
		
	if seasonManager then
		if seasonManager:IsRaining() then
			seasonManager:StopPrecip()
			print("Stopping rain.")
		else
			seasonManager:StartPrecip()
			print("Starting rain.")
		end
	end
end

function ToggleSpeed(multiplier)
	local inst = GetPlayer()
	local default_runspeed = TUNING.WILSON_RUN_SPEED

	if inst then
		if inst.components.locomotor.runspeed > default_runspeed then
			inst.components.locomotor.runspeed = default_runspeed
		else
			inst.components.locomotor.runspeed = default_runspeed * (multiplier or 3)
		end
	end
end

function ToggleTimeScale()
	local timescaleIsIncreased = TheSim:GetTimeScale() > 1

	if timescaleIsIncreased then
		TheSim:SetTimeScale(1)
	else
		TheSim:SetTimeScale(4)
	end
end

function Freebuild()
	local inst = GetPlayer()
	
	if inst then
		if inst.components.builder.freebuildmode then
			inst.components.builder.freebuildmode = false
		else
			inst.components.builder.freebuildmode = true
		end

		inst:PushEvent("techlevelchange")
	end
end

-- Character

function UnlockCharacters()
	local inst = GetPlayer()
	
	if inst then
		local profile = inst.profile
	
		local characters = {'willow', 'wendy', 'wolfgang', 'wilton', 'wx78', 'wickerbottom', 'wes'}
		for k,v in pairs(characters) do
			profile:UnlockCharacter(v)
		end
		
		print("Characters unlocked.")
	end
end

-- use this in the console instead of CharSelectScreen
function CharacterSelect()
	GetPlayer():DoTaskInTime(0, CharSelectScreen)
end

function CharSelectScreen()
		local player = GetPlayer()
		local profile = player.profile
		
		if player and profile then 
			local oldCharacter = player.prefab
			
			SetHUDPause(true)
			
			local cs_screen = CharacterSelectScreen(profile, 
				function(character) 
					if character and character ~= player.prefab then 
						
						local persistdata = player:GetPersistData()
						local pos = Point(player.Transform:GetWorldPosition())
						
						player:Remove()
						TheFrontEnd:ClearScreens()
						
						TheSim:LoadPrefabs({character})
						TheSim:UnloadPrefabs({oldCharacter})
						
						local prefab = SpawnPrefab(character)
						assert(prefab, "could not spawn player character")
						prefab.Transform:SetPosition(pos:Get())
						
						local hud = PlayerHud()
						TheFrontEnd:PushScreen(hud)
						
						prefab.SoundEmitter:SetMute(true)
						prefab:SetProfile(profile)

						local newents = {}
						prefab:SetPersistData(persistdata, newents)
						for k,v in pairs(newents) do
							v.entity:LoadPostPass(newents, v.data)
						end

						hud:SetMainCharacter(prefab)
						prefab.SoundEmitter:SetMute(false)
						SetUpPlayerCharacterCallbacks(prefab)			
						TheCamera:SetTarget(prefab)					
					end		
					
					SetHUDPause(false)				
				end), true	
				
			cs_screen:SelectCharacter(oldCharacter)
			TheFrontEnd:PushScreen(cs_screen)
		end
end

-- Map

function MapHide()
	local ground = GetWorld()
	
	if ground then
		ground.Map:ResetVisited()
		
		print("Map hidden, save and reload.")
	end
end

function MapReveal()
	local minimap = TheSim:FindFirstEntityWithTag("minimap")
	
	if minimap then
		minimap.MiniMap:EnableFogOfWar(false)
		
		print("Map revealed.")
	end
end

-- Misc

function NextSeason()
	local seasonManager = GetSeasonManager()
	
	if seasonManager then
		if seasonManager:IsWinter() then
			seasonManager:StartSummer()
		else
			seasonManager:StartWinter()
		end
		
		print("Changing season to ", seasonManager:GetSeasonString(), ".")
	end
end

function NextDay()
	GetClock():MakeNextDay()
end

function NextPhase()
	GetClock():NextPhase()
end

----

function Lightning()
	local seasonManager = GetSeasonManager()
	
	if seasonManager then
		local pt = Vector3(TheInput:GetMouseWorldPos():Get())
		seasonManager:DoLightningStrike(pt)
	end
end