require "TrapSystem"

local Commands = {}
local noise = TrapSystem.noise

function Commands.add(player, args)
	local trap = TrapSystem.getPlacedTrap(args.x, args.y, args.z)
	if trap then
		noise('client placed > 1 trap at '..args.x..','..args.y..','..args.z)
	else
		-- The client created the trap object already and sent it to the server.
		-- It would be better if the server created the trap object, not the client.
		local square = getCell():getGridSquare(args.x, args.y, args.z)
		if square then
			TrapSystem.loadTraps(square)
		end
	end
end

function Commands.remove(player, args)
	local trap = TrapSystem.getPlacedTrap(args.x, args.y, args.z)
	if trap then
		local item = InventoryItemFactory.CreateItem(trap.type)
		player:sendObjectChange('addItem', { item = item })
		trap:removeBait(player)
		TrapSystem.removeTrap(trap, true)
	else
		noise('no trap found at '..args.x..','..args.y..','..args.z)
	end
end

function Commands.removeAnimal(player, args)
	local trap = TrapSystem.getPlacedTrap(args.x, args.y, args.z)
	if trap then
		if trap.animal.type then
			trap:removeAnimal(player)
		else
			noise('no animal in trap at '..args.x..','..args.y..','..args.z)
		end
	else
		noise('no trap found at '..args.x..','..args.y..','..args.z)
	end
end

function Commands.addBait(player, args)
	local trap = TrapSystem.getPlacedTrap(args.x, args.y, args.z)
	if trap then
		trap:addBait(args.bait, args.age, player)
	else
		noise('no trap found at '..args.x..','..args.y..','..args.z)
	end
end

function Commands.removeBait(player, args)
	local trap = TrapSystem.getPlacedTrap(args.x, args.y, args.z)
	if trap then
		trap:removeBait(player)
	else
		noise('no trap found at '..args.x..','..args.y..','..args.z)
	end
end

function TrapSystem.OnClientCommand(module, command, player, args)
	if module ~= 'trapping' then return end
	if Commands[command] then
		local argStr = ''
		for k,v in pairs(args) do argStr = argStr..' '..k..'='..v end
		noise('OnClientCommand '..module..' '..command..argStr)
		Commands[command](player, args)
	end
end

Events.OnClientCommand.Add(TrapSystem.OnClientCommand)

