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 has exists"
    exe_ret["result"] = "5005"
    return cjson.encode(exe_ret)
end
if #ARGV%18 == 0 then
	exe_ret["error"] = "joinRoom.lua param error"
    return cjson.encode(exe_ret)
end
if #ARGV < 23 then
    exe_ret["error"] = "argv number is too little"
    return cjson.encode(exe_ret)
end

local playerList = {}
local playerInfo = {}
local playerID =  ARGV[5]
playerInfo["PlayerID"] = playerID
playerInfo["CarTplID"] = ARGV[6]
playerInfo["JoinTime"] = ARGV[7]
playerInfo["ExteriorRefit"] = ARGV[9]
playerInfo["ReadyState"] = 1
playerInfo["Proficiency"] = ARGV[10]
playerInfo["ProficiencyLv"] = ARGV[11]
playerInfo["Gender"] = ARGV[12]
playerInfo["Cloth"] = ARGV[13]
playerInfo["Head"] = ARGV[14]
playerInfo["NickName"] = ARGV[15]
playerInfo["Position"] = ARGV[16]
playerInfo["ScuffleScore"] = ARGV[17]
playerInfo["continuityWin"] = ARGV[18]
playerInfo["SkinColor"] = ARGV[19]
playerInfo["CarLv"] = ARGV[20]
playerInfo["PlayerLevel"] = ARGV[22]
playerInfo["PlayerDan"] = ARGV[23]
playerList[playerID] = playerInfo

local roomData = {}
roomData["RoomID"] = ARGV[1]
roomData["PlayerInfo"] = cjson.encode(playerList)
roomData["RoomName"] = ARGV[2]
roomData["MapID"] = ARGV[3]
roomData["RoomState"] = 1
roomData["PlayType"] = 1
roomData["ModeType"] = ARGV[4]
roomData["ChatID"] = ARGV[21]

--[[
	save hash data
--]]
redis.call('HSET' , KEYS[1], "RoomID" , ARGV[1])
redis.call('HSET' , KEYS[1], "PlayerInfo" , cjson.encode(playerList))
redis.call('HSET' , KEYS[1], "RoomName" , ARGV[2])
redis.call('HSET' , KEYS[1], "MapID" , ARGV[3])
redis.call('HSET' , KEYS[1], "RoomState" , 1)
redis.call('HSET' , KEYS[1], "PlayType" , 1)
redis.call('HSET' , KEYS[1], "ModeType" , ARGV[4])
redis.call('HSET' , KEYS[1], "InvitedInfo1" , "[]")
redis.call('HSET' , KEYS[1], "InvitedInfo2" , "[]")

--[[
	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_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_index = index_name(KEYS[1])
local table_time = index_time(KEYS[1])

--[[
	add zset roomID - create time
--]]
redis.call( 'ZADD' , table_time , ARGV[7] , ARGV[1] )

--[[
	add zset roomID - score
--]]
redis.call( 'ZADD' , table_index , ARGV[8] , ARGV[1] )

return cjson.encode(exe_ret)