local p3stats_saver = Class(function(self, inst)
    self.inst = inst
	
	
	self.plstats={}
	
	

	self.sharedstat = {}
	self.sharedstat["respawnsleft"] = TUNING.COOP_MOD_RESPAWNS
	self.sharedstat["notspawn"] = false

	self.inst:StartThread(function()
        for k = 0, 1 do
			self.plstats[k]={}
			local newplarray = self.plstats[k]
			--newplarray[""]
			newplarray["char"] = ""
			newplarray["health"] = 0
			newplarray["sanity"] = 0
			newplarray["hunger"] = 0
			newplarray["x"] = 0
			newplarray["y"] = 0
			newplarray["boatingwith"] = 0 ---- / 0 - grounded / 1 - with player -  / 2 - alone
			newplarray["boatingon"] = self.inst
		end
    end)	
	
	
	
    self.task = self.inst:DoPeriodicTask(20, function() self:Checkforrespawn(20) end)
end)


function p3stats_saver:GNA(targ)
	if not targ:HasTag("addedplayer") or (not targ.plnum) then return end
	if not self.plstats.[targ.plnum] then return end
	return self.plstats.[targ.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.sharedstat["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.sharedstat["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
	
	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")

		end
	
	end
	
	
end

function p3stats_saver:OnSave()
    local player2 = FindEntity(GetPlayer(), 100, function(guy) return (guy.components.playercontroller_3)end)
	local player = GetPlayer()
	
	if player2 then
		self:RecordStats(player2, "OnSave")
	end
		local a = self:GNA(player2)
		
        return 
		{
			savingarray = {} and savingarray[3] = {a["char"], a["health"], a["sanity"], a["hunger"], a["x"], a["y"], a["boatingwith"] }, -- and savingarray[2] = {a["char"], a["health"], a["sanity"], a["hunger"], a["x"], a["y"], a["boatingwith"]},
			respawnsleft = self.sharedstat["respawnsleft"] or TUNING.COOP_MOD_RESPAWNS

		}
		

	
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["boatingon"] = data.boatingon
		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() 
	
    local player2 = FindEntity(GetPlayer(), 125, function(guy) return (guy.components.playercontroller_3)end)
	if not player2 then 
		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)
		end
		return
	end
	
	self.stat["notspawn"] = true
	
	--player2.components.health:DoDelta(-10000)
--	player2:Remove()

	player2.components.playercontroller_3:DeleteWithStatsRecord()
		self.inst:DoTaskInTime(0.25, function()
			if self.stat["notspawn"] == true then
				GetPlayer().components.playercontroller_spawner:RespawnPlayer3()
			end	
		end)
    end)
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

