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 ~= 18 then
	exe_ret["error"] = "joinRoom.lua param error"
    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

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

if playerNum == tonumber(ARGV[1]) then
    exe_ret["error"] = "num max"
    exe_ret["result"] = "5003"
    return cjson.encode(exe_ret)
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["Position"] = ARGV[12]
newPlayerInfo["ScuffleScore"] = ARGV[13]
newPlayerInfo["continuityWin"] = ARGV[14]
newPlayerInfo["SkinColor"] = ARGV[15]
newPlayerInfo["CarLv"] = ARGV[16]
newPlayerInfo["PlayerLevel"] = ARGV[17]
newPlayerInfo["PlayerDan"] = ARGV[18]

playerList[newPlayerID] = newPlayerInfo

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


--[[
	get data index to add data index
--]]
local index_name = function ( key )
	local index = string.find(key, '}')
	index = string.find(key,'-',index + 2)
	local head  = string.sub(key, 1, index - 1)
	return head
end

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


local table_index = index_name(KEYS[1])
local room_id = index_id(KEYS[1])

local score =  tonumber(redis.call( 'ZSCORE' , table_index , room_id))
local new_score = score - ( score % 100 ) + playerNum + 1

--[[
	add data index
--]]
redis.call( 'ZADD' , table_index , new_score ,room_id )

return cjson.encode(exe_ret)

