--***********************************************************
--**                    ROBERT JOHNSON                     **
--***********************************************************

require "TimedActions/ISBaseTimedAction"

ISHarvestPlantAction = ISBaseTimedAction:derive("ISHarvestPlantAction");

function ISHarvestPlantAction:isValid()
	return self.plant:getObject() and self.plant:canHarvest()
end

function ISHarvestPlantAction:update()
end

function ISHarvestPlantAction:start()
end

function ISHarvestPlantAction:stop()
	ISBaseTimedAction.stop(self);
end

function ISHarvestPlantAction:perform()
	if isClient() then
		local sq = self.plant:getSquare()
		local args = { x = sq:getX(), y = sq:getY(), z = sq:getZ() }
		sendClientCommand(self.character, 'farming', 'harvest', args)
		-- we successfull harvest our plant, we may gain xp !
		basicFarming.gainXp(self.character, self.plant)
		-- needed to remove from queue / start next.
		ISBaseTimedAction.perform(self);
		return
	end
	
	local plant = self.plant;
	-- add all the item in the plant container into the player inventory
	local vegetable = farming_vegetableconf.props[plant.typeOfSeed].vegetableName;
	local numberOfVeg = getVegetablesNumber(farming_vegetableconf.props[plant.typeOfSeed].minVeg, farming_vegetableconf.props[plant.typeOfSeed].maxVeg, farming_vegetableconf.props[plant.typeOfSeed].minVegAutorized, farming_vegetableconf.props[plant.typeOfSeed].maxVegAutorized, plant);
	local items = self.character:getInventory():AddItems(vegetable, numberOfVeg);
	for i=1,items:size() do
		if items:get(i-1) then
			items:get(i-1):setLastAged(getGameTime():getWorldAgeHours())
		end
	end

	if plant.hasSeed then
		local seed = farming_vegetableconf.props[plant.typeOfSeed].seedName;
		self.character:getInventory():AddItems(seed, (farming_vegetableconf.props[plant.typeOfSeed].seedPerVeg * numberOfVeg));
	end

	plant.hasVegetable = false;
	plant.hasSeed = false;

	-- the strawberrie don't disapear, it goes on phase 2 again
	if plant.typeOfSeed == "Strawberry plant" then
		plant.nbOfGrow = 1;
		basicFarming.growPlant(plant, nil, true);
	else
        basicFarming.removePlant(plant);
	end

	-- we successfull harvest our plant, we may gain xp !
	basicFarming.gainXp(self.character, plant);
    -- needed to remove from queue / start next.
	ISBaseTimedAction.perform(self);
end

function ISHarvestPlantAction:new(character, plant, time)
	local o = {}
	setmetatable(o, self)
	self.__index = self
	o.character = character;
    o.plant = plant;
	o.maxTime = time;
	o.stopOnWalk = true;
	o.stopOnRun = true;
    o.caloriesModifier = 4;
	return o;
end
