AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include('shared.lua')
//----------------------------//

// Spawn
function ENT:SpawnFunction( ply, tr )
	if ( !tr.Hit ) then return end
	local SpawnPos = tr.HitPos + tr.HitNormal * 30
	local ent = ents.Create(self.ClassName)
	local angle = ply:GetAimVector():Angle()
	angle = Angle(0,angle.yaw,0)
	ent:SetAngles( angle )
	ent:SetPos( SpawnPos )
	ent:Spawn()
	ent:Activate()
	zpizmak.f.SetOwnerID(ent, ply)
	return ent
end
function ENT:Initialize()
	self:SetModel(self.Model)
	self:PhysicsInit( SOLID_VPHYSICS )
	self:SetMoveType( MOVETYPE_VPHYSICS )
	self:SetSolid( SOLID_VPHYSICS )
	self:SetUseType(SIMPLE_USE)
	self:SetCollisionGroup(COLLISION_GROUP_WEAPON )

	local phys = self:GetPhysicsObject()
	if (phys:IsValid()) then
		phys:Wake()
		phys:EnableMotion(true)
	end
	self:UseClientSideAnimation()

	self.NeededIngredients = {}
	self.InOven = false
end


////// Select Recipe
util.AddNetworkString("zpizmak_pizzadough_net")

function ENT:Use(activator, caller)
	if IsValid(activator) and activator:IsPlayer() then
		local pizzaState = self:GetCurrentState_Index()

		if (pizzaState == 3 or pizzaState == 4) then
			if (self.InOven == false) then
				local health = zpizmak.f.GetPizzaByName(self:GetPizzaType()).ConsumHealth

				if (health > 0) then
					if (pizzaState == 4) then
						health = health * 0.3
					end

					if (zpizmak.config.UseHungermod) then
						local newEnergy = math.Clamp((activator:getDarkRPVar("Energy") or 100) + (health or 1), 1, 100)
						activator:setSelfDarkRPVar("Energy", newEnergy)
					else
						local newHealth = activator:Health() + health

						if (zpizmak.config.HealthCap and (activator:Health() + health) > activator:GetMaxHealth()) then
							newHealth = activator:GetMaxHealth()
						end

						activator:SetHealth(newHealth)
					end
				end

				if (pizzaState == 3) then
					zpizmak.f.Notify(activator, zpizmak.language.PizzaConsum_Good, 0)
				elseif (pizzaState == 4) then
					zpizmak.f.Notify(activator, zpizmak.language.PizzaConsum_Bad, 1)
				end

				self:Remove()
			end
		elseif (zpizmak.f.IsOwner(activator, self) or zpizmak.config.EquipmentSharing) then
			if (zpizmak.f.JobRestriction(activator)) then
				if (self:GetCurrentState_Index() == 0) then
					net.Start("zpizmak_pizzadough_net")
					net.WriteEntity(self)
					net.Send(activator)
				end
			end
		end
	end
end

util.AddNetworkString("zpizmak_select_pizza")
net.Receive("zpizmak_select_pizza",function(len,ply)
	local val = net.ReadInt(16)
	local zpizmak_pizzadough = net.ReadEntity()

	if ( !IsValid(zpizmak_pizzadough) || zpizmak_pizzadough:GetClass() != "zpizmak_pizza" ) then
		return
	end

	if ply:GetPos():Distance(zpizmak_pizzadough:GetPos()) > 300 then
		return
	end

    if !ply:Alive() then
		return
	end

	zpizmak_pizzadough:SelectRecipe(zpizmak.config.Pizzas[val])
end)

util.AddNetworkString("zpizmak_update_cl_ingredients")
function ENT:SelectRecipe(PizzaData)
	self.SelectedRecipe = PizzaData.Name
	self:SetSelectedRecipe(self.SelectedRecipe)

	table.Empty(self.NeededIngredients)
	for k, v in pairs(PizzaData.Recipe) do
		for i = 1, v do
			table.insert(self.NeededIngredients, k)
		end
	end

	// This Updates the Visual Ingrediens Indicator on Client
	net.Start("zpizmak_update_cl_ingredients")
	net.WriteEntity(self)
	net.WriteTable(self.NeededIngredients)
	net.Broadcast()

	self:SetPizzaType(self.SelectedRecipe)
	self:Increase_PizzaState()
end
//////

////// Add Ingredients
util.AddNetworkString("zpizmak_add_cl_ingredient")
function ENT:Add_Ingredient(ing)
	local itemIng = ing:GetIngredient_Type()

	if(self:Needs_Ingredient(itemIng))then
		ing:Remove()
		table.remove( self.NeededIngredients, table.KeyFromValue( self.NeededIngredients, itemIng )  )

		// This Updates the Visual Ingrediens Indicator on Client
		net.Start("zpizmak_update_cl_ingredients")
		net.WriteEntity(self)
		net.WriteTable(self.NeededIngredients)
		net.Broadcast()


		net.Start("zpizmak_add_cl_ingredient")
		net.WriteEntity(self)
		net.WriteString(itemIng)
		net.Broadcast()

		if(table.Count(self.NeededIngredients) <= 0)then
			self:Increase_PizzaState()
		end
	end
end
function ENT:Needs_Ingredient(ing)
	local correctIngredient = false

	for k, v in pairs(self.NeededIngredients) do
		if(v == ing)then
			correctIngredient = true
			break
		end
	end
	return correctIngredient
end
//////



function ENT:Pizza_Bake()
	self:SetBakeTime(self:GetBakeTime() + 1)

	local currentBakeTime = self:GetBakeTime()

	local ply = zpizmak.f.GetOwner(self)
    local needBakeTime = zpizmak.f.GetPizzaByName(self:GetPizzaType()).BakeTime

    if(currentBakeTime >= needBakeTime + zpizmak.config.PizzaBurnTime)then

  	  zpizmak.f.Notify(ply, zpizmak.language.Pizza_Burned, 1 )
  	  if(self:GetCurrentState_Index() == 3)then
  		  self:Increase_PizzaState()
  	  end

    elseif(currentBakeTime == needBakeTime)then

  	  zpizmak.f.Notify(ply, zpizmak.language.Pizza_Ready, 0 )

	  zpizmak.f.CreateEffectTable(nil,"zpizmak_sfx_ovendone",self,self:GetAngles(),self:GetPos())
  	  if(self:GetCurrentState_Index() == 2)then
  		  self:Increase_PizzaState()
  	  end
    end

	local t = 0
	local pizzaColor = Color(48, 32, 23)

	if(self:GetCurrentState_Index() == 2)then
		t = (1/needBakeTime) * currentBakeTime
		pizzaColor = zpizmak.f.LerpColor(t, Color(255,255,255), Color(200,150,119))
	elseif(self:GetCurrentState_Index() == 3)then
		t = (1/zpizmak.config.PizzaBurnTime) * (currentBakeTime-needBakeTime)
		pizzaColor = zpizmak.f.LerpColor(t, Color(200,150,119), Color(48, 32, 23))
	end

	self:SetColor(pizzaColor)
end


function ENT:Increase_PizzaState()
	self:SetCurrentState_Index(self:GetCurrentState_Index() + 1)

	self:UpdateVisuals()
end
function ENT:UpdateVisuals()
	local state = self:GetCurrentState_Index()

	if(state == 1)then

		self:SetModel("models/zerochain/props_pizza/zpizmak_pizza.mdl")
		self:PhysicsInit( SOLID_VPHYSICS )
		self:SetMoveType( MOVETYPE_VPHYSICS )
		self:SetSolid( SOLID_VPHYSICS )

		local phys = self:GetPhysicsObject()
		if (phys:IsValid()) then
			phys:Wake()
			phys:EnableMotion(true)
		end

		self:SetAngles(Angle(0,0,0))

	elseif(state == 2)then
		self:SetSkin(1)
	elseif(state == 3)then
		self:SetColor(Color(200,150,119))
	elseif(state == 4)then
		self:SetColor( Color(91,61,43))
	end
end
