dofile("../defs/rarity_defs.lua")

Container = class("Container")

function Container:new(def, level, index)
	local container = instance(self)
	container.index = index
	container.def = def	
	container.level = level	
	return container
end

function Container:generate_rarity(rarity_factor)
	local def = self.def
	local rarity_roll = math.random()
	local rarity_factor = (def.rarity_factor or 1)*(rarity_factor or 1)
	for index, rdef in ipairs(RARITY_DEFS) do
		if rdef.threshold then
			local threshold = rdef.threshold*rarity_factor
			if rarity_roll <= threshold then
				return rdef.key
			end
		else
			return rdef.key
		end
	end
end

function Container:generate_one_stock(rules)
	local def = self.def
	local level = self.level
	local pool = def.items
	
	if pool then
		local total_pool = table.calculate_total_pool(pool)
		if total_pool > 0 then
			local roll = table.roll_pool(pool, total_pool)
			local rarity = self:generate_rarity()			
			local item = rules:generate_instance("item", roll, level, rarity)
			return item			
		end
	end
end


function Container:generate_loot(universe,x,y, rarity_factor)
	local def = self.def
	local level = self.level
	local pool = def.items
	
	local tried,success = false,false
	if pool then
		local total_pool = table.calculate_total_pool(pool)
		if total_pool > 0 then
			local min_picks = def.min_picks or 1
			local max_picks = def.max_picks or 1
			local picks = math.random(min_picks, max_picks)
			local rules = universe.rules

			for i=1,picks do
				local roll = table.roll_pool(pool, total_pool)
				local rarity = self:generate_rarity(rarity_factor)
				local rdef = RARITY_DEFS[rarity]
				local item = rules:generate_instance("item", roll, level, rarity)
				local pickup = Entity:new("pickup", x, y, 1)

				pickup:set_item(item)

				local angle = math.randomAngle()
				local force = rdef.loot_force*(0.75 + 0.25*math.random())
				local dx = math.cos(angle)*force
				local dy = math.sin(angle)*force
				pickup:set_speed(dx,dy,force*10)
				universe:add_ent(pickup)
				success = true
			end

			return true, success
		end
	end
	return false, false
end
