require "class"
require "screens/pausescreen"
local easing = require "easing"

local trace = function() end

local CLICK_WALK_TIME = .5

local prefabs =
{
	"ghostplayer",
	"summonclone",
	"camera_prefab",
}


local PlayerController_spawner = Class(function(self, inst)
    self.inst = inst
    self.enabled = true
    
    
    self.inputhandlers = {}

    table.insert(self.inputhandlers, TheInput:AddKeyUpHandler(KEY_P, function() self:SpawnPlayer2() end))
	
    table.insert(self.inputhandlers, TheInput:AddKeyUpHandler(KEY_DELETE, function() self:SpawnPlayer3("wilson") end))---1
    table.insert(self.inputhandlers, TheInput:AddKeyUpHandler(KEY_HOME, function() self:SpawnPlayer3("willow") end))---2
    table.insert(self.inputhandlers, TheInput:AddKeyUpHandler(KEY_INSERT, function() self:SpawnPlayer3("wolfgang") end))---3
    table.insert(self.inputhandlers, TheInput:AddKeyUpHandler(KEY_END, function() self:SpawnPlayer3("wendy") end))---4
    table.insert(self.inputhandlers, TheInput:AddKeyUpHandler(KEY_PAGEUP, function() self:SpawnPlayer3("wx78") end))----5
    table.insert(self.inputhandlers, TheInput:AddKeyUpHandler(KEY_PAGEDOWN, function() self:SpawnPlayer3("wickerbottom") end))----6
    table.insert(self.inputhandlers, TheInput:AddKeyUpHandler(KEY_RSHIFT, function() self:SpawnPlayer3("woodie") end))---7
    table.insert(self.inputhandlers, TheInput:AddKeyUpHandler(KEY_RCTRL, function() self:SpawnPlayer3("waxwell") end))---8
    table.insert(self.inputhandlers, TheInput:AddKeyUpHandler(KEY_ENTER, function() self:SpawnPlayer3("wes") end))---8
	
    table.insert(self.inputhandlers, TheInput:AddKeyUpHandler(KEY_Z, function() self:Camera() end))---7
	table.insert(self.inputhandlers, TheInput:AddKeyUpHandler(KEY_KP_MINUS, function() self:RespawnPlayer3("respawn") end))
	
	
    table.insert(self.inputhandlers, TheInput:AddKeyDownHandler(KEY_X, function() self:CameraPrefab() end))---7
    table.insert(self.inputhandlers, TheInput:AddKeyDownHandler(KEY_C, function() self:Defence() end))---7

end)

function PlayerController_spawner:Camera()
    TheCamera:SetTarget(self.inst)
end


function PlayerController_spawner:CameraPrefab()
    local cameraprefab = FindEntity(GetPlayer(), 1000, function(guy) return (guy.components.playercontroller_camera)end)
	if cameraprefab then
		cameraprefab.components.health:DoDelta(-9000)
	end
	
    local ghostplayer = SpawnPrefab("camera_prefab")
    ghostplayer.Transform:SetPosition(GetPlayer().Transform:GetWorldPosition())
    TheCamera:SetTarget(ghostplayer)
	ghostplayer.components.playercontroller_camera.camfocus = 1
	
end
----deftorch

function PlayerController_spawner:Defence()
if TUNING.DEFENCEOFF==1 then
 print("coop def is off")
 return
end

    local cameraprefab = FindEntity(self.inst, 1000, function(guy) return (guy:HasTag("deftorch"))end)
if cameraprefab then
	cameraprefab.components.health:DoDelta(-9000)
			
			


end	
            local ghostplayer = SpawnPrefab("deftorch")
            ghostplayer.Transform:SetPosition(self.inst.Transform:GetWorldPosition())
    self.inst.components.inventory:ConsumeByName("ash", 4)
    self.inst.components.inventory:ConsumeByName("torch", 1)



		
end

function PlayerController_spawner:SpawnPlayer2()
if TUNING.GHOSTPLAYERON==1 then return end
            local ghostplayer = SpawnPrefab("ghostplayer")
            ghostplayer.Transform:SetPosition(self.inst.Transform:GetWorldPosition())
		if self.inst.components.health.currenthealth > 50 then
			self.inst.components.health:SetPercent(.5)
			self.inst.components.hunger:SetPercent(.5)
			self.inst.components.sanity:SetPercent(.5)
		end			
end

function PlayerController_spawner:RespawnPlayer3(tag)
	if GetPlayer().components.p3stats_saver.stat["respawnsleft"]<1 then
		print("==== NO LIFES LEFT CAN NOT RESPAWN!===")
		return
	end


			if self.inst:HasTag("RespawnPlayer3") then
					self.inst:DoTaskInTime(5, function()	
					self.inst:RemoveTag("RespawnPlayer3")
					return
				end)
				return
			end
			
			---find and kill existing player3
			local player2 = FindEntity(GetPlayer(), 100, function(guy) return (guy.components.playercontroller_3)end)
			if player2 then
				GetPlayer().components.p3stats_saver:RecordStats(player2,"PlayerController_spawner:RespawnPlayer3")			
				player2.components.playercontroller_3:DeleteWithStatsRecord(true)
			end
			
			TheCamera:SetTarget(self.inst)
			
			local player1 = GetPlayer()
			
            local summonclone = SpawnPrefab("summonclone")
			local player3 = summonclone
			
			local hp = 1
			local sanity = 1
			local hunger = 1
			local x = 0
			local y = 0
			local dead = false
			local p1tohealth = 1
			
			
		if self.inst:HasTag("notspawn") or player1.components.p3stats_saver.stat["notspawn"] == true then
			hp = player1.components.p3stats_saver.stat["health"]
			sanity = player1.components.p3stats_saver.stat["sanity"]
			hunger = player1.components.p3stats_saver.stat["hunger"]
			x = player1.components.p3stats_saver.stat["x"]
			y = player1.components.p3stats_saver.stat["y"]
			print("===136  POSITION pos;  x "..x.."  y:"..y)
			if hp<0.01 then
				dead = true
				hp = 0.35
				p1tohealth = p1tohealth-0.65

				self.inst.components.sanity:DoDelta(-25,true)
				self.inst.components.hunger:DoDelta(-25,true)
			end
			if hunger<0.01 then
				hunger = 0.35
				p1tohealth = p1tohealth-0.15
				
				self.inst.components.sanity:DoDelta(-5,true)
				self.inst.components.hunger:DoDelta(-5,true)
			end
			if self.inst.components.health:GetPercent()<p1tohealth then
				self.inst.components.health:SetPercent(p1tohealth)
			end
		end
			if not player3 then
				print("WTF?!")
				return
			end
			print("CHAR :  "..player1.components.p3stats_saver.stat["char"].."=====:stat  hp: "..hp.." stat hunger: "..hunger)
			player3.components.health:SetPercent(hp)
			player3.components.hunger:SetPercent(sanity)
			player3.components.sanity:SetPercent(hunger)
			

		
		if x~=0 and not dead == true then
			print("MOVING TO POS")
			--player3.Physics:Teleport(x, 0, y) 
			player3.Transform:SetPosition(x, 0, y)
		else
			player3.Transform:SetPosition(self.inst.Transform:GetWorldPosition())
		end
		
		if dead == true then
			player1.components.p3stats_saver:RespawnDelta(-1,player3)
			player3.sg:GoToState("wakeup")

		else
			print("====RESPAWN -=NOT=- COUNTED on summonclone  RESPAWNS LEFT = ".. player1.components.p3stats_saver.stat["respawnsleft"])
		end

			self.CameraPrefab()
			

			self.inst.components.sanity:DoDelta(-1,true)
			self.inst.components.hunger:DoDelta(-1,true)
			
			
			self.inst:AddTag("notspawn")
			player1.components.p3stats_saver.stat["notspawn"] = true

			
   if player3.components.driver then
	if (player1.components.driver.driving == true and dead == true) or (player1.components.p3stats_saver.stat["boatingwith"] and player1.components.p3stats_saver.stat["boatingwith"] ==1) then
		player3.components.playercontroller_3:MountBoat()
		player3.mountedvehicle = player1.components.driver.vehicle
	elseif player1.components.p3stats_saver.stat["boatingwith"]==2 then
		print("BOATING  WITH == 2")
		local emptyboatnear	= FindEntity(player3, 2, function(guy) return (guy.components.drivable and not guy:HasTag("NOCLICK") and guy.components.boathealth and not guy.components.boathealth:IsDead()) end)
		if emptyboatnear then
			print("206 BOAT FoUND")
			player3.startupdatingboatwithplayer = false
			local action = ACTIONS.MOUNT
			local ba = BufferedAction(player3, emptyboatnear, action)
			player3.mountedvehicle = emptyboatnear
			player3.components.locomotor:PushAction(ba, true)
			player3.boatingwith = 2
			player3:RemoveComponent("Player3KeepOnLand")
		end
	else
		player3:AddComponent("Player3KeepOnLand")

	
	end
	player3.components.playercontroller_3:GiveSpecialItems()

	
	
   end
end

function PlayerController_spawner:SpawnPlayer3(tag)
	local player1 = GetPlayer()
	if not self.inst:HasTag("notspawn") and player1.components.p3stats_saver.stat["notspawn"] == false then
			self.inst:AddTag(tag)
			player1.components.p3stats_saver.stat["char"] = tag
			
			print("tag = "..tag)
			print("p3stats_saver.stat  char  = "..player1.components.p3stats_saver.stat["char"])
			self:RespawnPlayer3(tag)
	end
end



return PlayerController_spawner
