AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include("shared.lua")

------------------------------//
function ENT:SpawnFunction(ply, tr)
	if (not tr.Hit) then return end
	local SpawnPos = tr.HitPos + tr.HitNormal * 1
	local ent = ents.Create(self.ClassName)
	local angle = ply:GetAimVector():Angle()
	angle = Angle(0, angle.yaw, 0)
	angle:RotateAroundAxis(angle:Up(), 180)
	ent:SetAngles(angle)
	ent:SetPos(SpawnPos)
	ent:Spawn()
	ent:Activate()

	return ent
end

function ENT:Initialize()
	self:SetModel(zrmine.config.BuyerNPC_Model)
	self:SetSolid(SOLID_BBOX)
	self:SetHullSizeNormal()
	self:SetNPCState(NPC_STATE_SCRIPT)
	self:SetHullType(HULL_HUMAN)
	self:SetUseType(SIMPLE_USE)
	self:SetMaxYawSpeed(90)
	self:CapabilitiesAdd(CAP_ANIMATEDFACE)
	self:CapabilitiesAdd(CAP_TURN_HEAD)
	self:DropToFloor()
	self:SetCollisionGroup(COLLISION_GROUP_WEAPON)

	timer.Simple(1, function()
		if (IsValid(self)) then
			zrmine.f.CreateAnimTable(self, zrmine.config.BuyerNPC_anim_idle[math.random(#zrmine.config.BuyerNPC_anim_idle)], 1)
			self:RefreshBuyRate()
		end
	end)
end

------------------------------//
function ENT:RefreshBuyRate()
	self:SetBuyRate(math.random(zrmine.config.BuyerNPC_MinRate, zrmine.config.BuyerNPC_MaxRate))
end

------------------------------//
function ENT:AcceptInput(key, ply)
	if ((self.lastUsed or CurTime()) <= CurTime()) and (key == "Use" and IsValid(ply) and ply:IsPlayer() and ply:Alive()) then
		self.lastUsed = CurTime() + 0.25

		-- Is the Player a customer of the BuyerNPC
		if (zrmine.f.IsMetalBuyerCustomer(ply)) then
			-- Does the Player have metal do sell
			if (zrmine.f.HasPlayerMetal(ply)) then
				-- Here we sell the bars
				zrmine.f.SellBars(ply, self)

				--Vrondakis
				if (LevelSystemConfiguration or manolis) then
					ply:addXP(zrmine.config.Vrondakis["Selling"].XP, " ", true)
				end

				-- Play the Sell Animation
				self:AnimSequence(zrmine.config.BuyerNPC_anim_sell[math.random(#zrmine.config.BuyerNPC_anim_sell)], zrmine.config.BuyerNPC_anim_idle[math.random(#zrmine.config.BuyerNPC_anim_idle)], 1)
			else
				zrmine.f.Notify(ply, zrmine.language.NPC_NoProduct, 1)
			end
		else
			zrmine.f.Notify(ply, zrmine.language.NPC_GoAway, 1)
		end
	end
end

------------------------------//
-- Animation
function ENT:AnimSequence(anim1, anim2, speed)
	zrmine.f.CreateAnimTable(self, anim1, speed)

	timer.Simple(self:SequenceDuration(self:GetSequence()), function()
		if (not IsValid(self)) then return end
		zrmine.f.CreateAnimTable(self, anim2, speed)
	end)
end

------------------------------//
function ENT:OnTakeDamage(dinfo)
end

function ENT:OnRemove()
end

------------------------------//
-- Save
local function zrms_Save_BuyerNPC()
	local data = {}

	for u, j in pairs(ents.FindByClass("zrms_buyer")) do
		table.insert(data, {
			class = j:GetClass(),
			pos = j:GetPos(),
			ang = j:GetAngles()
		})
	end

	if not file.Exists("zrms", "DATA") then
		file.CreateDir("zrms")
	end

	file.Write("zrms/" .. game.GetMap() .. "_BuyerNPCs" .. ".txt", util.TableToJSON(data))
end

local function zrms_Load_BuyerNPC()
	if file.Exists("zrms/" .. game.GetMap() .. "_BuyerNPCs" .. ".txt", "DATA") then
		local data = file.Read("zrms/" .. game.GetMap() .. "_BuyerNPCs" .. ".txt", "DATA")
		data = util.JSONToTable(data)

		for k, v in pairs(data) do
			local oreSpawner = ents.Create("zrms_buyer")
			oreSpawner:SetPos(v.pos)
			oreSpawner:SetAngles(v.ang)
			oreSpawner:Spawn()
		end

		print("[Zeros Retro MiningSystem] Finished loading Buyer NPCs.")
	else
		print("[Zeros Retro MiningSystem] No map data found for BuyerNPCs entities. Please place some and do !savezrms to create the data.")
		end
	end

	hook.Add("InitPostEntity", "zrms_SpawnBuyerNPC", zrms_Load_BuyerNPC)
	hook.Add("PostCleanupMap", "zrms_SpawnBuyerNPCPostCleanUp", zrms_Load_BuyerNPC)

	hook.Add("PlayerSay", "zrms_SaveBuyerNPC", function(ply, text)
		if string.sub(string.lower(text), 1, 9) == "!savezrms" then
			if zrmine.f.IsAdmin(ply) then
				zrms_Save_BuyerNPC()
				zrmine.f.Notify(ply, "BuyerNPC´s have been saved for the map " .. game.GetMap() .. "!", 0)
			else
				zrmine.f.Notify(ply, "You do not have permission to perform this action, please contact an admin.", 1)
				end
			end
		end)
