-- read namespace from global env
local _G = _G
local Grichelde = _G.Grichelde

local pairs, find, toNumber = Grichelde.functions.pairs, Grichelde.functions.find, Grichelde.functions.toNumber

function Grichelde:Upgrade_To_v060()
    self:PrefixedPrint(self.L.Upgrade_ToVersion, Grichelde.COLOR_CODES.ORANGE .. "0.6.0" .. Grichelde.COLOR_CODES.CLOSE)

    local replacements = self.db.profile.replacements or {}
    self:DebugPrint("Upgrade_To_060 : old database")
    self:DebugPrint(replacements)

    for _, replTable in pairs(replacements) do
        replTable["ignoreCase"] = not replTable["caseSensitive"]
        replTable["caseSensitive"] = nil
    end

    self:DebugPrint("Upgrade_To_060 : new database")
    self:DebugPrint(replacements)
    return 0, 6, 0
end

function Grichelde:Upgrade_To_v070()
    self:PrefixedPrint(self.L.Upgrade_ToVersion, Grichelde.COLOR_CODES.ORANGE .. "0.7.0" .. Grichelde.COLOR_CODES.CLOSE)

    local replacements = self.db.profile.replacements or {}
    self:DebugPrint("Upgrade_To_070 : old database")
    self:DebugPrint(replacements)

    for _, replTable in pairs(replacements) do
        replTable["exactCase"] = not replTable["ignoreCase"]
        replTable["ignoreCase"] = nil
    end

    self:DebugPrint("Upgrade_To_070 : new database")
    self:DebugPrint(replacements)
    return 0, 7, 0
end

--[[
function Grichelde:Upgrade_To_v071()
    return 0, 7, 1
end
]]

function Grichelde:UpgradeDatabase()
    local dbVersion = self.db.global.version or "0.0.0"
    self:DebugPrint("Database version:", dbVersion)

    local _, _, maj, min, pat = find(dbVersion, "(%d+)%.(%d+)%.(%d+).*")
    local major, minor, patch = toNumber(maj) or 0, toNumber(min) or 0, toNumber(pat) or 0

    local upgrade = 0
    local error = false

    if major == 0 then
        if minor < 6 then
            upgrade = upgrade + 1
            major, minor, patch = self:Upgrade_To_v060(dbVersion)
        end
        if minor < 7 then
            upgrade = upgrade + 1
            major, minor, patch = self:Upgrade_To_v070(dbVersion)
        end
--[[
        if minor == 7 then
            if patch < 1 then
                upgrade = upgrade + 1
                major, minor, patch = self:Upgrade_To_v71(dbVersion)
            end
        end
]]
    end

    if upgrade == 0 then
        self:DebugPrint("Database up-to-date")
    else
        if not error then
            self.db.global.version = self.version
            self:PrefixedPrint(Grichelde.COLOR_CODES.GREEN .. self.L.Upgrade_Successful .. Grichelde.COLOR_CODES.CLOSE)
        end
    end
end