local exe_ret = {}
exe_ret["error"] = "success"
exe_ret["result"] = ""

--[[
	check condition
--]]
local ret = redis.call('EXISTS' , KEYS[1])
if ret == 0 then
    exe_ret["error"] = "key not exists"
    exe_ret["result"] = "5002"
    return cjson.encode(exe_ret)
end
if #ARGV ~= 16 then
	exe_ret["error"] = "param error:not 15"
    return cjson.encode(exe_ret)
end

local newPlayerID =  ARGV[2]

--[[
      search max
--]]
local ret = redis.call('HGET' , KEYS[1], "PlayerInfo" )
local playerList = cjson.decode(ret)

local playerNum = 0
local playerWatchNum = 0

for k, v in pairs(playerList) do
    if v["Role"] == "1" or v["Role"] == 1 then
        playerNum = playerNum + 1
        if k == newPlayerID then
            exe_ret["error"] = "player has exists"
            exe_ret["result"] = "5001"
            return cjson.encode(exe_ret)
        end
    else
        playerWatchNum = playerWatchNum + 1
    end
end

local index_time = function ( key )
    local index = string.find(key, '}')
    index = string.find(key,'-',index + 2)
    local head  = string.sub(key, 1, index - 1)
    return head .. 'Time'
end

local table_time = index_time(KEYS[1])

if ARGV[14] == "1" or ARGV[14] == 1 then
    if playerNum >= tonumber(ARGV[1]) then
        exe_ret["error"] = "num max"
        exe_ret["result"] = "5003"
        return cjson.encode(exe_ret)
    end

    --[[
    	add zset roomID - update time
    --]]
    redis.call( 'ZADD' , table_time , ARGV[15], ARGV[13] )
else
    if playerWatchNum >= tonumber(ARGV[1]) then
        exe_ret["error"] = "num max"
        exe_ret["result"] = "5003"
        return cjson.encode(exe_ret)
    end
end

local newPlayerInfo = {}
newPlayerInfo["PlayerID"] = newPlayerID
newPlayerInfo["CarTplID"] = ARGV[3]
newPlayerInfo["JoinTime"] = ARGV[4]
newPlayerInfo["ReadyState"] = 1
newPlayerInfo["ExteriorRefit"] = ARGV[5]
newPlayerInfo["Proficiency"] = ARGV[6]
newPlayerInfo["ProficiencyLv"] = ARGV[7]
newPlayerInfo["Gender"] = ARGV[8]
newPlayerInfo["Cloth"] = ARGV[9]
newPlayerInfo["Head"] = ARGV[10]
newPlayerInfo["NickName"] = ARGV[11]
newPlayerInfo["Team"] = ARGV[12]
newPlayerInfo["Role"] = ARGV[14]
newPlayerInfo["CarLv"] = ARGV[16]

playerList[newPlayerID] = newPlayerInfo

--[[
	save hash data
--]]
local ret = redis.call('HSET' , KEYS[1], "PlayerInfo" , cjson.encode(playerList))


return cjson.encode(exe_ret)

