--[[
Items change to other items over time
By Nolan Ritchie

NO NEED TO EDIT ANYTHING HERE
ONLY EDIT timetracker_definitions.lua

]]

function loadItem(Item)
	
	if(ItemTimeTrackerMod[Item:getType()] ~= nil) then
		itemFound = true;
		Item:getModData().Life = ItemTimeTrackerMod[Item:getType()]["Life"];
		Item:getModData().TurnInto = ItemTimeTrackerMod[Item:getType()]["TurnInto"];
		Item:getModData().StartTime = getGameTime():getWorldAgeHours();
		return true;
	else
		return false;
	end
		

end

function ContainerHandle(container)

	local items = container:getItems();
	for i=0,items:size()-1 do
		if (items:get(i):getCategory() == "Container") then 
			ContainerHandle(items:get(i):getItemContainer()) ;
		else
			if(items:get(i):getModData().Life == nil) then
				loadItem(items:get(i));
			else
				--getPlayer():Say(tostring(items:get(i):getType()));
				--items:get(i):getModData().Life = items:get(i):getModData().Life - (getGameTime():getWorldAgeHours() - items:get(i):getModData().Life);
				if(items:get(i):getModData().Life < (getGameTime():getWorldAgeHours() - items:get(i):getModData().StartTime)) then
					local temp = container:AddItem(items:get(i):getModData().TurnInto);
					if (temp) then loadItem(temp) end ;
					container:Remove(items:get(i));
				end
			end
		end
	end

end

function WorldItemHandle(item,square)

	if (item:getCategory() == "Container") then 
			ContainerHandle(item:getItemContainer()) ;
	else
		if(item:getModData().Life == nil) then
			loadItem(item);
		else
			--getPlayer():Say(tostring(item:getType()));
			--item:getModData().Life = item:getModData().Life - (getGameTime():getWorldAgeHours() - item:getModData().Life);
			if(item:getModData().Life < (getGameTime():getWorldAgeHours() - item:getModData().StartTime)) then
		
				local WI = item:getWorldItem();
				square:transmitRemoveItemFromSquare(WI);
				WI:removeFromSquare();
				
				local temp = square:AddWorldInventoryItem(item:getModData().TurnInto, 0.5, 0.5, 0);			
				if (temp) then loadItem(temp) end ;
			end
		end
	end

end

function ItemCheck()
	
	ContainerHandle(getPlayer():getInventory());
	
	local cell = getWorld():getCell();
	for x=(cell:getMinX()+10), (cell:getMaxX()-10) do
		for y=(cell:getMinY()+10), (cell:getMaxY()-10) do
			for z=(cell:getMinZ()), (cell:getMaxZ()) do
			
				local sq = cell:getGridSquare(x,y,z);
				if(sq ~= nil) then
					local items = sq:getObjects();
					for j=0, items:size()-1 do
						if(items:get(j):getContainer() ~= nil) then
							ContainerHandle(items:get(j):getContainer());
						end
					end
					local items = sq:getWorldObjects();
					for j=0, items:size()-1 do
						if(items:get(j):getItem()) then
							WorldItemHandle(items:get(j):getItem(),sq);
						end
					end
				end
				
			end
		end
	end
	
	
end

--Events.EveryDays.Add(ItemCheck);
Events.EveryTenMinutes.Add(ItemCheck);
