local RULES = dofile("../defs/rule_defs.lua")

Rules = class("Rules")

function Rules:new(seed, min_level, max_level)
	local rules = instance(self)
	rules.seed = seed
	rules.min_level = min_level
	rules.max_level = max_level
	rules:generate()
	return rules
end

function Rules:init_tables()
	self.items = {}
	self.monsters = {}
	self.areas = {}
	self.shops = {}
	self.skills = {}
	self.containers = {}
end

local function index_sort(a,b)
	return a.index < b.index
end

local function get_verified_order(rule_block)
	assert(rule_block.categories, "no categories")
	if not rule_block.order then
		local order = {}
		for cat, cat_def in pairs(rule_block.categories) do
			table.insert(order, {index = cat, def = cat_def})
		end
		shellsort(order, index_sort)
		rule_block.order = order
	end
	return rule_block.order
end

function Rules:generate()
	local seed = self.seed
	local min_level = self.min_level
	local max_level = self.max_level
	assert(seed, "no seed")
	assert(min_level, "no min_level")
	assert(max_level, "no max_level")

	self:init_tables()
	math.initRandom(seed)

	--local ordered_rules = get_verified_order(RULES)
	--for _, ordered in ipairs(ordered_rules) do
	--	local rule_cat = ordered.def
	--	for level = min_level, max_level do
--
	--		--Generating level rules
	--	end
	--end
end

function Rules:get_categories(rule_set)
	return RULES[rule_set].categories
end

function Rules:generate_instance(rule_set, category, level, rarity)
	local rules = RULES[rule_set]
	assert(rules, rule_set, "is not in RULES")
	local def = rules.categories[category]
	assert(def, category, "category missing in RULES[", rule_set)
	local instance = rules.generate(self, def, level, category, rarity)
	return assert(instance,"instance not returned", rule_set, category, level)
end