local CraftItemSystem = inherited("CraftItemSystem", SystemMap)

function CraftItemSystem:new()
	local ms = instance(self)
	return ms
end

function CraftItemSystem:dynamic_wants(ent)
	return ent.aspects.crafter and ent.craft_slot
end

function CraftItemSystem:ent_added(ent)
end

function CraftItemSystem:ent_removed(ent)
end

function CraftItemSystem:step(dt)
	for ent, _ in pairs(self.ents) do
		local craft_slot = ent.craft_slot
		if craft_slot then
			local item = craft_slot:get_item()
			if item then		
				--print("ss")
				local craft_container = item.def.craft_container
				if craft_container and item:has_stack() then
				--	print("ssss")
					local universe = self.world.universe
					local stack_size = item:get_stack()
					local faction = math.ceil(stack_size*0.33)
					local rarity_factor = faction/item.def.level_range
					local level_peak = item.def.level_peak - item.def.level_range*0.5 + math.min(item.def.level_range, faction)
					local container = universe.rules:generate_instance("container", craft_container, level_peak)
					local tried, succeess = container:generate_loot(universe, ent.x, ent.y, rarity_factor)
					if tried then
						if not succeess then
							ent:emit_feedback_text(20, "Failed!", COLORS.bad, 1)
						else
							ent:emit_feedback_text(20, "Success!", COLORS.good, 1)
							ent:set_feedback("craft", 1)
						end
						item:adjust_stack(-faction)
						if item:get_stack() <= 0 then
							craft_slot:clear_item()	
							if ent.inventory_changed then
								ent:inventory_changed()
							end
						end				
					else
						ent:emit_feedback_text(20, "Not enough "..item:get_core_name().."!", COLORS.bad, 1)
					end
				end
			end
			ent:set_craft_slot_intent(nil)
		end
	end
end

return CraftItemSystem