--[[
	PlayerServer.lua

	AddPlayerAddedFunc:
		Add a function that runs whenever a player joins a server

]]


local this = {}
this.__index = this

this.Service = nil

function  this.new(  )
	-- body
	local self = this.Service or {}
	setmetatable(self,this)


	self.BindedPlayerAddedFunctions = {}
	self.BindedCharacterAddedFunctions = {}
	self.BindedPlayerRemovingFunctions = {}

	for _,v in pairs(game.Players:GetPlayers()) do
		self:PlayerAdded(v)
	end
	self.Connections = {
		PlayerAdded = game.Players.PlayerAdded:Connect(function(plr)
			self:PlayerAdded(plr)
		end);
		PlayerRemoving = game.Players.PlayerRemoving:Connect(function(plr)
			self:PlayerRemoving(plr)
		end);
	}

	this.Service = self
	return self
end

function this:PlayerAdded( plr )
	for _,v in pairs(self.BindedPlayerAddedFunctions) do
		v(plr)
	end
	if plr.Character then
		self:CharacterAdded(plr.Character)
	end
	plr.CharacterAdded:Connect(function( char )
		self:CharacterAdded(char)
	end)
end

function  this:PlayerRemoving( plr )
	for _,v in pairs(self.BindedPlayerRemovingFunctions) do
		v(plr)
	end
end

function this:CharacterAdded(char)
	for _,v in pairs(self.BindedCharacterAddedFunctions) do
		v(char)
	end
end

function  this:AddPlayerAddedFunc(name, func )
	-- body
	self.BindedPlayerAddedFunctions[name] = func
	for i,v in pairs(game.Players:GetPlayers()) do
		warn(v.Name.. " was already in the game before we added this player added function")
		func(v)
	end
end

function  this:AddPlayerRemovingFunc(name, func )
	-- body
	self.BindedPlayerRemovingFunctions[name] = func
end

function  this:AddCharacterAddedFunc(name, func )
	-- body
	self.BindedCharacterAddedFunctions[name] = func
	for i,v in pairs(game.Players:GetPlayers()) do
		if v.Character then
			warn(v.Name.. " was already in the game before we added this Character added function")
			func(v.Character)
		end
	end
end

function this:Deconstruct() -- Delete the player's object

end

return this
