local p3stats_saver = Class(function(self, inst)
    self.inst = inst
	
	
	self.stat={}
	
	self.stat["char"] = ""
	self.stat["health"] = 0
	self.stat["sanity"] = 0
	self.stat["hunger"] = 0
	self.stat["notspawn"] = false
	self.stat["x"] = 0
	self.stat["y"] = 0
	self.stat["boatingwith"] = 0 -- / 0 - grounded / 1 - with player -  / 2 - alone
	
	self.stat["passenger"] = 0 -- / 0 - grounded / 1 - with player 1  / 2 - with player 2  /  3 - with player 3   / 4 - alone

	
	self.stat["boatingon"] = self.inst
	self.stat["respawnsleft"] = TUNING.COOP_MOD_RESPAWNS
	
	self.stat[3] = false
	self.stat[2] = false
	
	self.shstats = {}
	self.shstats[3] = {}
	self.shstats[2] = {}
	

	--self.shstats[2] = {}
	--self.stat[22] = {}
	--self.stat[22][1] = {"array1test"}
	--print(self.stat[22][1][1])
	
    self.task = self.inst:DoPeriodicTask(30, function() self:Checkforrespawn(20) end)
end)


function p3stats_saver:ShouldRespawnNum(plnum)


end

function p3stats_saver:Checkforrespawn(dt)
	print("============Check for respawn============")
   --[[ local player2 = FindEntity(GetPlayer(), 125, function(guy) return (guy.components.playercontroller_3)end)
	if not player2 and self.stat["notspawn"] == true then 
			--self.inst:RemoveTag("notspawn")
			--self.stat["notspawn"] = false
			print("PERIODIC CHECK! No second player ---- AUTO RESPAWN!!!")
			GetPlayer().components.playercontroller_spawner:RespawnPlayer3()
		return
	end
	if not player2 and self.stat["notspawn"] == false then 
		if TUNING.PICK_CHAR_IN_WORLD == 0 then
			print("No second player and character selected in config ---- AUTO SPAWN!!!")
			GetPlayer().components.playercontroller_spawner:SpawnPlayer3(TUNING.PLAYER_3_CHARACTER)
		end
	end--]]
	
	
	
	local respawn2needed = self.inst.components.playercontroller_spawner:IsRespawnNeeded(2, true)
	local respawn3needed = self.inst.components.playercontroller_spawner:IsRespawnNeeded(3, true)

	if respawn2needed==true and TUNING.PLAYER_CHARACTER_ENABLED[2]==true then
		print("SHOULD RESPAWN ... PLAYER")
		
		if self.inst.components.playercontroller_spawner:WasPlayerByNumSpawned(2)==false and TUNING.PICK_CHAR_IN_WORLD == 0 then
			self.inst.components.playercontroller_spawner:TryToRespawn(TUNING.PLAYER_2_CHARACTER, 2, true, true)
			print("1s time")

		elseif self.inst.components.playercontroller_spawner:WasPlayerByNumSpawned(2)==true then
			print("as a respawn")
			self.inst.components.playercontroller_spawner:TryToRespawn(TUNING.PLAYER_2_CHARACTER, 2, false, true)
		else ---WTF respawn is needed and it doesn't fit previous variants! RESPAWN ANYWAY!!!!!!!!!!
			print("WTF respawn is needed and it doesn't fit previous variants! RESPAWN ANYWAY!!!!!!!!!!")
			self.inst.components.playercontroller_spawner:TryToRespawn(TUNING.PLAYER_2_CHARACTER, 2, false, true)
		end
	end 
	

	if respawn3needed==true and TUNING.PLAYER_CHARACTER_ENABLED[3]==true then
		print("SHOULD RESPAWN ... PLAYER")
		if self.inst.components.playercontroller_spawner:WasPlayerByNumSpawned(3)==false and TUNING.PICK_CHAR_IN_WORLD == 0 then
			self.inst.components.playercontroller_spawner:TryToRespawn(TUNING.PLAYER_3_CHARACTER, 3, true, true)
			print("1s time")

		elseif self.inst.components.playercontroller_spawner:WasPlayerByNumSpawned(3)==true then
			print("as a respawn")
			self.inst.components.playercontroller_spawner:TryToRespawn(TUNING.PLAYER_3_CHARACTER, 3, false, true)
		end
	end 	
	
	
	local function boatfix(number)
		local player2 = self.inst.components.playercontroller_spawner:FindPlayerByNum(number)
		if player2 and player2.components.driver then
			local isboating = player2.components.playercontroller_3:IsReallyBoating()
			if isboating==false and player2.boatingwith ~=0 then
				print("p3stats_saver:Checkforrespawn")
				print("isboating==false")
				print("CORRECRING")

				--player2:AddComponent("Player3KeepOnLand")
				player2.boatingwith =0
				player2.startupdatingboatwithplayer = true
				
				ChangeToCharacterPhysics(player2)
				player2.Physics:SetActive(true)
				
				player2:RemoveTag("UnMountBoat")
				player2:RemoveTag("CheckingSailor")
				player2:RemoveTag("aquatic")

			end
		end
	end 
	boatfix(2)
	boatfix(3)
	

end



function p3stats_saver:OnSave()
   --- local player2 = FindEntity(GetPlayer(), 100, function(guy) return (guy.components.playercontroller_3)end)
	local player = GetPlayer()

	
	local player2 = self.inst.components.playercontroller_spawner:FindPlayerByNum(2)
	local player3 = self.inst.components.playercontroller_spawner:FindPlayerByNum(3)
	
	
	
	
	
	if player2 then
		self:RecordStatsSeparate(player2, "OnSave")
	end
	if player3 then
		self:RecordStatsSeparate(player3, "OnSave")
	end
	
        return {
		p3spawned = self.stat[3],
		p2spawned = self.stat[2],
		chara = self.stat["char"],
		health = self.stat["health"],
		sanity = self.stat["sanity"],
		hunger = self.stat["hunger"],
		notspawn = self.stat["notspawn"],
		x = self.stat["x"],
		y = self.stat["y"],
		boatingwith = self.stat["boatingwith"],
		respawnsleft = self.stat["respawnsleft"] or TUNING.COOP_MOD_RESPAWNS,
		char2 = self.shstats[2]["char"],
		char3 = self.shstats[3]["char"],
		}
		
		
end


function p3stats_saver:RespawnDelta(a, inst)
	local d = a or -1
	self.stat["respawnsleft"] = self.stat["respawnsleft"] + d
	local pref = (inst and inst.prefab) or " TIME "

	if self.stat["respawnsleft"]>TUNING.COOP_MOD_RESPAWNS or TUNING.COOP_MOD_RESPAWNS==322 then
		self.stat["respawnsleft"] = TUNING.COOP_MOD_RESPAWNS
	end
	print("====RESPAWN COUNTED on ( "..pref.." )  RESPAWNS LEFT = ".. self.stat["respawnsleft"])

end


function p3stats_saver:OnLoad(data)
		self.stat={}
		self.stat["char"]= data.chara
		self.stat["health"]= data.health
		self.stat["sanity"]= data.sanity
		self.stat["hunger"] = data.hunger
		self.stat["notspawn"] = data.notspawn
		self.stat["x"] = data.x
		self.stat["y"] = data.y
		self.stat["boatingwith"] = data.boatingwith
		self.stat["respawnsleft"] = data.respawnsleft or TUNING.COOP_MOD_RESPAWNS
		
		self.stat[3] = data.p3spawned or false
		self.stat[2] = data.p2spawned or false
			

		self.shstats = {}
		self.shstats[3] = {}
		self.shstats[2] = {}
		self.shstats[2]["char"] = data.char2 or TUNING.PLAYER_2_CHARACTER
		self.shstats[3]["char"] = data.char3 or TUNING.PLAYER_3_CHARACTER
		
		
		
		print("===================TUNING.PLAYER_3_CHARACTER===  "..TUNING.PLAYER_3_CHARACTER)
		print("==RESPAWNS LEFT == "..self.stat["respawnsleft"])
	--[[	if TUNING.PICK_CHAR_IN_WORLD == 0 then
			print("===================2nd player set to:  "..TUNING.PLAYER_3_CHARACTER)
			self.stat["char"] = TUNING.PLAYER_3_CHARACTER
		end--]]
---find player 3 and set his stats
		--print("LOADED: "..self.stat["char"])
	--	print(self.stat["notspawn"])
		
	self.inst:DoTaskInTime(1, function() 
	
	
	
		self:Checkforrespawn()	
	
	
	--[[
	local player3 = self.inst.components.playercontroller_spawner:FindPlayerByNum(3)
	local player2 = self.inst.components.playercontroller_spawner:FindPlayerByNum(2)

	if not player3 then 
		print("player3 not found! is he dead or wasn't spawned yet?")
		if self.stat[3] == false then print("WASN't spawned yet, respawn here!") end
		if self.stat[3] == true then print("DEAD! p3stats_saver job here is done") return end
		
		self.stat["notspawn"] = false
		if TUNING.PICK_CHAR_IN_WORLD == 0 then
			print("No second player and character selected in config ---- AUTO SPAWN!!!")
			GetPlayer().components.playercontroller_spawner:SpawnPlayer3(TUNING.PLAYER_3_CHARACTER)
		else
			print("No second player and character selected in world ----let player do it")
		end
	end
	
	--self.stat["notspawn"] = true
	
--]]
    end)
end


function p3stats_saver:RecordStatsSeparate(targ, reason, dd)
			local dead = dd or false


			if targ:GetPosition().x == 0 then
				print("====== RecordStatsSeparate = x ==0 SCREW DAT RECORD!!!")
				return
			end
			if targ.plnum == nil then targ.plnum = 2 end
			print("==========RECORD STATS _S E P A R A T E_==========")
			print("=======PREFAB ".. targ.prefab.."   PLAYER NUMBER = "..targ.plnum)
			local rsn = reason or "Why not?"
			print("==========REASON:  "..rsn)
			local player = GetPlayer()
			local plnum = targ.plnum 
			player.components.p3stats_saver.shstats[plnum]["char"] = targ.newplayername-- or "wilson"
			player.components.p3stats_saver.shstats[plnum]["health"] = targ.components.health:GetPercent()
			player.components.p3stats_saver.shstats[plnum]["hunger"] = targ.components.hunger:GetPercent()
			player.components.p3stats_saver.shstats[plnum]["sanity"] = targ.components.sanity:GetPercent()
			
			player.components.p3stats_saver.shstats[plnum]["x"] = targ:GetPosition().x
			player.components.p3stats_saver.shstats[plnum]["y"] = targ:GetPosition().z
			
			player.components.p3stats_saver.shstats[plnum]["boatingwith"] = targ.boatingwith
			if player.components.poisonable and player.components.poisonable:IsPoisoned() == true then
				dead = true
				print("======POISON DEATH")
			end
			
			if dead==true then player.components.p3stats_saver.shstats[plnum]["health"] = 0 end
		--	print("==========STATS RECORDED printing==========")
			local name1 = player.components.p3stats_saver.shstats[plnum]["char"]
			local hp = player.components.p3stats_saver.shstats[plnum]["health"]
			local hunger = player.components.p3stats_saver.shstats[plnum]["hunger"]
			local x = player.components.p3stats_saver.shstats[plnum]["x"]
			local y = player.components.p3stats_saver.shstats[plnum]["y"]
			if hp<0.1 then
				print("=====DEAD!!! REASON OF RECORD..  "..rsn)
				
			end
			print("STATS: name:"..name1.. "   x:"..x.." y: "..y)
			print("==========STATS RECORDED END _S E P A R A T E_==========")



end


function p3stats_saver:RecordStats(player3, reason, dead)

			if player3:GetPosition().x == 0 then
				print("====== RecordStats = x ==0 SCREW DAT RECORD!!!")
				return
			end
			print("==========RECORD STATS==========")
			local rsn = reason or "Why not?"
			--print("==========REASON:  "..rsn)
			local player = GetPlayer()
			
			player.components.p3stats_saver.stat["health"] = player3.components.health:GetPercent()
			player.components.p3stats_saver.stat["hunger"] = player3.components.hunger:GetPercent()
			player.components.p3stats_saver.stat["sanity"] = player3.components.sanity:GetPercent()
			
			player.components.p3stats_saver.stat["x"] = player3:GetPosition().x
			player.components.p3stats_saver.stat["y"] = player3:GetPosition().z
			
			player.components.p3stats_saver.stat["boatingwith"] = player3.boatingwith
			
			
			if dead then player.components.p3stats_saver.stat["health"] = 0 end
		--	print("==========STATS RECORDED printing==========")
			
			local hp = player.components.p3stats_saver.stat["health"]
			local hunger = player.components.p3stats_saver.stat["hunger"]
			local x = player.components.p3stats_saver.stat["x"]
			local y = player.components.p3stats_saver.stat["y"]
			if hp<0.1 then
				print("=====DEAD!!! REASON OF RECORD..  "..rsn)
			end
			print("STATS: x:"..x.." y: "..y)
			print("==========STATS RECORDED END==========")



end


return p3stats_saver

