-----------------------------------------------
-- 星空争霸/王者争霸 db

-- getThroneList        获取王座列表
-- getThroneByVestId    根据_id获取王座信息
-----------------------------------------------

local ThroneExcel = require("excel.throne")
local LuaMongo = _G.lua_mongo
local Config = require("Config")
local DB = require("common.DB")

ID_2_THRONE = ID_2_THRONE or {}                     -- id->throne
VESTID_2_THRONE = VESTID_2_THRONE or {}             -- _id->throne

local DBUpdate = {_id = nil}                         


-- 初始化单个王座信息
local function initThrone(id)
    local throne = {}
    throne.id = id                  -- 王座id
    throne.lv = 1                   -- 挑战等级
    throne.record = {}              -- 记录
    throne.uuid = nil               -- 占领者uuid
    throne.body = nil               -- 形象
    throne.exp = nil                -- 当前经验值
    throne.evolve = nil             -- 已进化x次
    return throne
end

-- 初始化
function init()
    if #ID_2_THRONE > 0 then return end

    LuaMongo.find(DB.db_the_stars)
    while true do
        local throne = {}
        if not LuaMongo.next(throne) then
            break
        end          
        ID_2_THRONE[throne.id] = throne
    end
    for id in ipairs(ThroneExcel.throne) do
        local throne = ID_2_THRONE[id]
        if not throne then
            throne = initThrone(id)
            LuaMongo.insert(DB.db_the_stars, throne)
            ID_2_THRONE[id] = throne                   
        end
        VESTID_2_THRONE[throne._id] = throne  
    end
end

function getThroneList()  
    return ID_2_THRONE
end

function getThroneByVestId(vestId)
    return vestId and VESTID_2_THRONE[vestId]
end


function updateThroneDB(throne)
    if not throne then return end
    if not throne._id then return end

    DBUpdate._id = throne._id
    LuaMongo.update(DB.db_the_stars, DBUpdate, throne)
    return true
end

-- 设置占领者
function setThroneRole(id, uuid, body, lv, exp, evolve)
    local throne = id and ID_2_THRONE[id]
    if not throne then return end

    unsetThroneRole(uuid)           -- 取消之前的占领

    throne.uuid = uuid
    throne.body = body
    throne.lv = lv
    throne.exp = exp
    throne.evolve = evolve
    
    updateThroneDB(throne)
end

-- 取消占领者
function unsetThroneRole(uuid)
    if not uuid then return end

    for _, throne in ipairs(ID_2_THRONE) do
        if throne.uuid == uuid then
            throne.uuid = nil 
            throne.body = nil 
            updateThroneDB(throne)            
        end
    end
end

