AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
AddCSLuaFile( "ships.lua" )
AddCSLuaFile( "cl_radials.lua" )
AddCSLuaFile( "cl_frettapanels.lua" )
include( "shared.lua" )
include("frettastuff.lua")
CreateConVar("DS_CreditRate", 1)
CreateConVar("DS_Test1", 0)
CreateConVar("DS_Test2", 0)
CreateConVar("DS_Test3", 0)
CreateConVar("DS_Test4", 0)
CreateConVar("DS_Test5", 0)

function DS_AddPlayerScore( ply )
 
	ply.Damage = 0
	ply.Credits = 15000
 
end
 
hook.Add( "PlayerInitialSpawn", "DS_AddPlayerScore", DS_AddPlayerScore )

function SpawnHook(pl)
pl.PowerDis = Vector(2,2,2)
end
hook.Add("PlayerSpawn", "PlayerSpawnHook", SpawnHook)


function ShipSelectCall( ply )
 
	ply:ConCommand( "ShipSelect" )
end
 
hook.Add("ShowSpare1", "ShipSelect", ShipSelectCall)


function DS_ScoreUpdate(dmginfo, ent)
local attacker = dmginfo:GetAttacker()
local dmgamount = dmginfo:GetDamage()
--Msg(attacker)
if attacker:IsValid() then
attacker.Damage = attacker.Damage + dmgamount
attacker.Credits = attacker.Credits + (dmgamount * server_settings.Int("DS_CreditRate"))
end
end


function wNRGup( ply, cmd, arg )
   if ply.PowerDis.x <= 3 then 
   ply.PowerDis.x = ply.PowerDis.x + 1
	if ply.PowerDis.y >= 2 then
	ply.PowerDis.y = ply.PowerDis.y - 1
	else
	ply.PowerDis.z = ply.PowerDis.z - 1
	end
	umsg.Start("wUp", ply)
	umsg.End()
	ChangeMods(ply)
   end
end

function sNRGup( ply, cmd, arg )
   if ply.PowerDis.y <= 3 then 
   ply.PowerDis.y = ply.PowerDis.y + 1
	if ply.PowerDis.z >= 2 then
	ply.PowerDis.z = ply.PowerDis.z - 1
	else
	ply.PowerDis.x = ply.PowerDis.x - 1
	end
	umsg.Start("sUp", ply)
	umsg.End()
	ChangeMods(ply)
   end
end

function eNRGup( ply, cmd, arg )
   if ply.PowerDis.z <= 3 then 
   ply.PowerDis.z = ply.PowerDis.z + 1
	if ply.PowerDis.x >= 2 then
	ply.PowerDis.x = ply.PowerDis.x - 1
	else
	ply.PowerDis.y = ply.PowerDis.y - 1
	end
	umsg.Start("eUp", ply)
	umsg.End()
	ChangeMods(ply)
   end
end

function wNRGdown( ply, cmd, arg )
   if ply.PowerDis.x >= 1 then 
   ply.PowerDis.x = ply.PowerDis.x - 1
	if ply.PowerDis.z <= 2 then
	ply.PowerDis.z = ply.PowerDis.z + 1
	else
	ply.PowerDis.y = ply.PowerDis.y + 1
	end
	umsg.Start("wDown", ply)
	umsg.End()
	ChangeMods(ply)
   end
end

function sNRGdown( ply, cmd, arg )
   if ply.PowerDis.y >= 1 then 
   ply.PowerDis.y = ply.PowerDis.y - 1
	if ply.PowerDis.x <= 2 then
	ply.PowerDis.x = ply.PowerDis.x + 1
	else
	ply.PowerDis.z = ply.PowerDis.z + 1
	end
	umsg.Start("sDown", ply)
	umsg.End()
	ChangeMods(ply)
   end
end

function eNRGdown( ply, cmd, arg )
   if ply.PowerDis.z >= 1 then 
   ply.PowerDis.z = ply.PowerDis.z - 1
	if ply.PowerDis.y <= 2 then
	ply.PowerDis.y = ply.PowerDis.y + 1
	else
	ply.PowerDis.x = ply.PowerDis.x + 1
	end
	umsg.Start("eDown", ply)
	umsg.End()
	ChangeMods(ply)
   end
end

local WeaponBonuses = {0.02, 0.03, 0.04, 0.05, 0.06}
local ShieldBonuses = {0.5, 0.75, 1, 1.25, 1.5}
local EngineBonuses = {0.02, 0.03, 0.04, 0.05, 0.06}

function ChangeMods(ply)
local ent = ply:GetNetworkedEntity("SpaceShip")
	if ent:IsValid() then
	ent.SpeedMod = EngineBonuses[ply.PowerDis.z + 1]
	ent.ShieldMod = ShieldBonuses[ply.PowerDis.y + 1]
	ent.WeaponMod = WeaponBonuses[ply.PowerDis.x + 1]
	end
end

//Maintenece Stuff

function DS_UpdateAll()
	for k,v in pairs (player.GetAll()) do
		if v:IsValid() then
		umsg.Start("CreditUpdate",v)
		umsg.Long(v.Credits)
		umsg.End()
		end
	end
timer.Simple(1, function() DS_UpdateAll() end)
end
timer.Simple(5, function() DS_UpdateAll() end)

function ShieldRegenThink()
	for k,v in pairs (player.GetAll()) do
	if v:IsValid() then
	local ship = v:GetNetworkedEntity("SpaceShip")
		if ship:IsValid() then
			if ship.dt.Shields ~= nil then
			local currentshields = ship.dt.Shields
			local FinalMaxShields = ship.MaxShields * ship.ShieldMod
				if currentshields  < FinalMaxShields then
				ship.dt.Shields = math.Clamp(ship.dt.Shields + (FinalMaxShields * ship.ShieldRegen),currentshields, FinalMaxShields)
				elseif ship.dt.Shields ~= FinalMaxShields then
				ship.dt.Shields = math.Clamp(ship.dt.Shields - (currentshields * ship.ShieldRegen),0, currentshields)
				end
			
				if ship.Energy < ship.MaxEnergy then
				ship.Energy = math.Clamp(ship.Energy + (ship.MaxEnergy * ship.WeaponMod),0,ship.MaxEnergy)
				umsg.Start("NRGUpdate",v)
				umsg.Short(ship.Energy)
				umsg.End()
				end
				
				if ship.ABFuel < ship.MaxABFuel then
				ship.ABFuel = math.Clamp(ship.ABFuel + (ship.MaxABFuel * ship.SpeedMod),0,ship.MaxABFuel)
				umsg.Start("ABFUpdate",v)
				umsg.Short(ship.ABFuel)
				umsg.End()
				end
			end
		end
	end
	end
timer.Simple(1, function() ShieldRegenThink() end)
end
timer.Simple(5, function() ShieldRegenThink() end)
--local ArmorAddons = {0.5, 0.75, 1, 1.2, 1.5}
--local ShieldAddons = {0.5, 0.75, 1, 1.25, 1.5}
--local EngineAddons = {0.5, 0.75, 1, 1.25, 1.5}

function LoadoutConfirmed(ply, cmd, arg)
local cleaned_args = {}
	for k,v in pairs(arg) do
	table.insert(cleaned_args, tonumber(v))
	end
cleaned_args[1] = math.Clamp(cleaned_args[1],1,3)
cleaned_args[2] = math.Clamp(cleaned_args[2],1, #ShipTypes[cleaned_args[1]])
local RequestedShip = ShipTypes[cleaned_args[1]][cleaned_args[2]]
	for k,v in pairs(cleaned_args) do
		if k > 2 && k <= #RequestedShip["Hardpoints"] then
		--print(#HardpointTypes[RequestedShip["Hardpoints"][k - 2]])
		--PrintTable(HardpointTypes[RequestedShip["Hardpoints"][k - 2]])
		cleaned_args[k] = math.Clamp(v, 1, table.Count(HardpointTypes[RequestedShip["Hardpoints"][k - 2]]))
		end
	end
--PrintTable(cleaned_args)

--PrintTable(RequestedShip)
	local ent = ents.Create(RequestedShip["ent_name"])
	if ply.Credits >= RequestedShip["Cost"] then
	ply.Credits = ply.Credits - RequestedShip["Cost"]
	local teampos = Vector(0,0,0)
	if ply:Team() == 1 then
	Vector(12425.3750+math.Rand(-75,75),-12471.9063+math.Rand(-75,75),-4891.5938+math.Rand(-75,75))
	else
	Vector(-12741.8750+math.Rand(-75,75),11844.5000+math.Rand(-75,75),-5146.5000+math.Rand(-75,75))
	end
	ent:SetPos(ply:GetPos())
	ent:Spawn()
	ent:GetPhysicsObject():EnableMotion(false)
	ent.Team = ply:Team()
	local HullAddons = 0
	local ShieldAddons = 0
	local EngineAddons = 0

	ent.MaxHull = RequestedShip["Hull"] + (RequestedShip["Hull"] * HullAddons)
	ent.MaxShields = RequestedShip["Shields"] + (RequestedShip["Shields"] * ShieldAddons)
	ent.ShieldRegen = RequestedShip["ShieldRegen"]
	ent.MaxABFuel = RequestedShip["ABFuel"]
	ent.ABFuel = ent.MaxABFuel
	ent.ForwardSpeed = ent.ForwardSpeed + (ent.ForwardSpeed * EngineAddons)
	ent.FastForwardSpeed = ent.FastForwardSpeed + (ent.FastForwardSpeed * EngineAddons)
	ent.BackwardSpeed = ent.BackwardSpeed + (ent.BackwardSpeed * EngineAddons)
	ent.SpeedMod = EngineBonuses[ply.PowerDis.z + 1]
	ent.ShieldMod = ShieldBonuses[ply.PowerDis.y + 1]
	ent.WeaponMod = WeaponBonuses[ply.PowerDis.x + 1]
	ent.MaxEnergy = RequestedShip["Energy"]
	ent.Energy = ent.MaxEnergy
	ent.Team = ply:
	InsertPilot(ent, ply)
	SendPersonalShipUpdate(ply, ent.MaxHull, ent.MaxShields, ent.MaxEnergy, ent.MaxABFuel)
	ent:Activate()
	ent.dt.MaxHull = ent.MaxHull
	ent.dt.MaxShields = ent.MaxShields
	--SendEveryoneData(ent, ent.MaxHull, ent.MaxShields)
		for k,v in pairs (RequestedShip["Hardpoints"]) do
	--local hp = RequestedShip["Hardpoints"][k][cleaned_args[k-2]
	local thisarg = cleaned_args[k+2]
		/*if thisarg <= 3 then
			if thisarg == 3 then
			EngineAddons = EngineAddons + 0.075
			elseif thisarg == 2 then
			ShieldAddons = ShieldAddons + 0.1
			else
			HullAddons = HullAddons + 0.2
			end
		else*/
		--PrintTable(HardpointTypes[v])
		
		/*if v == "Light" then
		table.insert(ent.Hardpoints, FighterWeaponFunctions[cleaned_args[k+2]])
		end*/
		--PrintTable(cleaned_args)
		--PrintTable(HardpointTypes[v][cleaned_args[k-2]])
		local ent_name = HardpointTypes[v][cleaned_args[k+2]][2]
			local wep1 = ents.Create(ent_name)
			wep1:SetPos(ent:LocalToWorld(RequestedShip["HardpointAngPos"][k][2]))
			wep1:SetAngles(RequestedShip["HardpointAngPos"][k][1])
			table.insert(ent.Hardpoints, wep1)
			wep1.Ship = ent
			wep1:Spawn()
			wep1.Team = ent.Team
			if v ~= "Light" then
			constraint.Weld(ent,wep1,0,0,0,true)
			end
			wep1:Activate()
	
		--end
	end
		ent:GetPhysicsObject():Wake()
		ent:GetPhysicsObject():EnableMotion(true)
		--timer.Simple(1, function() InsertPilot(ent, ply) end)
	end
	
end
function SendPersonalShipUpdate(ply, MH, MS,ME, fuel)
	umsg.Start("ShipMaxes", ply)
	umsg.Vector(Vector(MH,MS,ME))
	umsg.Short(fuel)
	umsg.End()
end

function SendEveryoneData(ent, MH, MS)
--Msg("Sending X " .. tostring(ent))
local rp = RecipientFilter()
rp:AddAllPlayers()     
	umsg.Start("OtherShipStatUpdate", rp)
	umsg.Entity(ent)
	umsg.Long(MH)
	umsg.Short(MS)
	umsg.End()
end
function InsertPilot(ent, ply)
		ent.dt.InFlight = true
		ent.dt.ply = ply
		ent.dt.Team = 2
		ent.dt.Shields = ent.MaxShields
		ent.dt.Hull = ent.MaxHull
		ply:SetNetworkedBool("isDriveShuttle",true)
		ply:SetNetworkedEntity("SpaceShip",ent)
		ply:Spectate( OBS_MODE_CHASE )
		ply:DrawViewModel(false)
		ply:DrawWorldModel(false)
		ply:StripWeapons()
end

/*---------------------------------------------------------
   Name: gamemode:PlayerSpawn( )
   Desc: Called when a player spawns
---------------------------------------------------------*/
function GM:PlayerSpawn( pl )

	//
	// If the player doesn't have a team in a TeamBased game
	// then spawn him as a spectator
	//
	if ( self.TeamBased && ( pl:Team() == TEAM_SPECTATOR || pl:Team() == TEAM_UNASSIGNED ) ) then

		self:PlayerSpawnAsSpectator( pl )
		return
	
	end

	// Stop observer mode
	pl:UnSpectate()

	// Call item loadout function
	hook.Call( "PlayerLoadout", GAMEMODE, pl )
	
	// Set player model
	hook.Call( "PlayerSetModel", GAMEMODE, pl )
	
	// Set the player's speed
	GAMEMODE:SetPlayerSpeed( pl, 250, 500 )
	
end

function DS_FireDisrupter(ent, num)
if ent.Energy >= 50 then
local pos = ent:LocalToWorld(ent.HardpointAngPos[num][2])

--PrintTable(pos .. " /n\n")
--local ang = ent:LocalToWorld(ent.HardpointAngPos[num][1])
local ang = ent:GetForward()
--Msg(ang)
		local bullet = {};
		bullet.Num = 1;
		bullet.Src = Vector(100,100,100)
		bullet.Dir = ang
		bullet.Spread = Vector (0, 0, 0);
		bullet.Tracer = 1;
		bullet.Force = 0;
		bullet.Damage = 1;
		bullet.TracerName = "Tracer";
ent:FireBullets (bullet);
		local fx = EffectData();
		fx:SetOrigin(pos);
		fx:SetAngle(ang);
		fx:SetScale(0.25);
		util.Effect("MuzzleEffect", fx);
		ent:EmitSound("Weapon_P90.Single", 100, 100);
ent.Energy = ent.Energy - 50
end
end

FighterWeaponFunctions = {DS_FireDisrupter}

--USE THIS TO ALLOW MOUSE TARGETING OF SHIPS AND CLIENTSIDE SHIELD MOVING

function GM:ContextScreenClick(aimvec,mousecode,pressed,ply)


end



concommand.Add("LoadoutConfirmed", LoadoutConfirmed)
concommand.Add("sNRGup", sNRGup)
concommand.Add("sNRGdown", sNRGdown)
concommand.Add("wNRGup", wNRGup)
concommand.Add("wNRGdown", wNRGdown)
concommand.Add("eNRGup", eNRGup)
concommand.Add("eNRGdown", eNRGdown)
