local addonName, addon = ...
local childName = addon['childName']
local child = addon[childName]
local modName = "autogreed"
local events = {}
local db
-- local L = LibStub('AceLocale-3.0'):GetLocale(childName, true)
local orbList = {
	[45087] = true, -- runed orb
	[52078] = true, -- chaos orb
}

local defaults = {
    ['deGreen'] = true,
    ['passGreen'] = false,
    ['deBlue'] = true,
    ['passBlue'] = false,
    ['deEpic'] = false,
    ['passEpic'] = false,
    ['skipNeed'] = true,
    ['ignoreOrbs'] = true,
    ['showBOE'] = 2,
    ['skipQuality'] = 0,
    ['skipQuest'] = true,
    ['skipPet'] = true,
    ['skipMount'] = true,
    ['skipHoliday'] = true,
}

local function getPref2(key)
	local db = child['MH_GetDB'](modName, defaults)
	return db[key]
end

local function getPref(pref)
	return getPref2(pref[#pref])
end

local function setPref(pref,value)
	local db = child['MH_GetDB'](modName, defaults)
	db[pref[#pref]] = value
end

local function checkPrefType(key, prefType)
	local db = child['MH_GetDB'](modName, defaults)
	if(type(getPref2(key)) ~= prefType) then
		db[key] = defaults[key]
	end
end

local function initDBCheck()
	for key,value in pairs(defaults) do
		checkPrefType(key, type(defaults[key]))
	end
end

local qualityTab = {'', 'Green', 'Blue', 'Epic', 'Legendary'}

local function START_LOOT_ROLL(_, event, id, ...)
	if (not id) then return	end
    local itemLink = GetLootRollItemLink(id)
    local itemID = GetItemInfoInstant(itemLink)
	if(getPref2('ignoreOrbs') and orbList[itemID]) then return end
	local _, _, _, quality, bop, canNeed, canGreed, canDE = GetLootRollItemInfo(id)
	local showNeed = getPref2('skipQuality') >= 0 and getPref2('skipQuality') or (GetAverageItemLevel() - 18)
	local _,_,_,itemLevel,_,_,_,_,_,_,_, classID, subclassID = GetItemInfo(itemLink)
	if(classID == 12 and getPref2('skipQuest')) then
		return
	elseif(classID == 15) then
		if(subclassID == 5 and getPref2('skipMount')) then
			return
		elseif(subclassID == 2 and getPref2('skipPet')) then
			return
		elseif(subclassID == 3 and getPref2('skipHoliday')) then
			return
		end
	end
	if(canNeed and bop and getPref2('skipNeed')) then
		if(showNeed < itemLevel) then
			return
		end
	end
	local arg1,arg2 = canDE and 3 or 2, 2
    local qname = qualityTab[quality]
	if(bop) then
		RollOnLoot(id, getPref2(format('de', qname)) and arg1 or arg2)
	else
		if(canNeed and quality > getPref2('showBOE') and getPref2('skipNeed')) then return end
		if(getPref2('greedBOE')) then
			RollOnLoot(id, getPref2(format('pass', qname)) and nil or (quality == 2 and arg1 or arg2))
		else
			RollOnLoot(id, arg1 == 3 and 3 or (getPref2(format('pass', qname)) and nil or arg1))
		end
	end
end
local init = {
    Setup = function(self)
        db = child['db']
        if(db[modName]) then
            child:RegisterEvent(events)
        end
        child:AddCE(modName)
    end
}
addon.RegisterCallback(init, format('Init%s', childName), 'Setup')