local meta = FindMetaTable("Player")

if SERVER then
	util.AddNetworkString("Party_NetworkChat")

	local whisper = PartySystem.WhipserCommand
	local cmd_length = #whisper
	hook.Add("PlayerSay", "Party_ChatFunctions", function(ply, text)
		if string.Left(text, cmd_length + 1) == (whisper.." ") then
			local text = string.sub(text, cmd_length + 2)
			ply:BroadCastPartyChat(text)
			return ""
		end
	end)

	function meta:InvitePlayer(ply)
		if !self:IsPartyMaster() then
			Party_ColoredMessage(self, Color(255, 50, 50), "Du bist nicht der Partyleiter!")
			return
		end
		if !IsValid(ply) then
			Party_ColoredMessage(self, Color(255, 50, 50), "Spieler konnte nicht gefunden werden!")
			return
		end
		if self:IsSameParty(ply) then
			Party_ColoredMessage(self, Color(255, 50, 50), "Spieler gehört bereits deiner Party an!")
			return
		end
		if ply:HasParty() then
			Party_ColoredMessage(self, Color(255, 50, 50), "Spieler gehört bereits einer anderen Party an!")
			return
		end
		if table.Count(self:GetParty().Players) >= PartySystem.MaxPartyPlayerAmount then
			Party_ColoredMessage(self, Color(255, 50, 50), "Deine Party ist bereits voll!")
			return
		end
		ply.party_invited = ply.party_invited or {}
		if ply.party_invited[self] and ply.party_invited[self] > CurTime() then
			Party_ColoredMessage(self, Color(255, 50, 50), "Du hast diesen Spieler erst kürzlich in deine Party eingeladen!")
			return
		end
		ply.party_invited[self] = CurTime() + 30
		net.Start("Party_ShowInviteMenu")
			net.WriteString(self:EntIndex())
		net.Send(ply)
		Party_ColoredMessage(self, color_white, ply:Name(), Color(50, 200, 50), " wurde in die Party eingeladen.")
	end

	function meta:BroadCastPartyChat(text)
		local partynum = self:GetCurrentPartyNumber()
		if partynum == 0 then
			Party_ColoredMessage(self, Color(255, 50, 50), "Du bist in keiner Party!")
			return
		end
		for _,v in pairs(PartyList[partynum].Players or {}) do
			v:SendPartyChat(self, text)
		end
	end

	function meta:SendPartyChat(ply, text)
		net.Start("Party_NetworkChat")
			net.WriteEntity(ply)
			net.WriteString(text)
		net.Send(self)
	end
end

if CLIENT then
	net.Receive("Party_NetworkChat", function(len)
		local sender = net.ReadEntity()
		if !IsValid(sender) then return end
		local text = net.ReadString()
		chat.AddText(Color(0, 63, 255), "(Party) ", Color(127, 159, 255), sender:Name()..": ", Color(255, 255, 255), text)
	end)
end

function meta:IsSameParty(target)
	local mn = self:GetCurrentPartyNumber()
	local tn = target:GetCurrentPartyNumber()
	if mn == tn and mn != 0 then
		return true
	else
		return false
	end
end

function meta:IsPartyMaster()
	if self.PartyMaster then return true end
	return false
end

function meta:HasParty()
	if self.Party then return true end
	return false
end

function meta:GetParty()
	return self.Party
end

function meta:GetCurrentPartyNumber()
	return self.PartyID or 0
end