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 ~= 2 then
	exe_ret["error"] = "param error:not 2"
    return cjson.encode(exe_ret)
end

local roomID = ARGV[1]
local delPlayerID =  ARGV[2]

--[[
      search player info
--]]
local ret = redis.call('HGET' , KEYS[1], "PlayerInfo" )
local playerList = cjson.decode(ret)
local playerNum = 0
local isHave    = 0

for k, v in pairs(playerList) do
    playerNum = playerNum + 1
    if k == delPlayerID then
        isHave = isHave + 1
        playerList[k] = nil
    end
end

if isHave == 0 then
    exe_ret["error"] = "exit room but player not find!"
    exe_ret["result"] = "5004"
    return cjson.encode(exe_ret)
end

--[[
	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

--[[
	get data id
--]]
local key_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 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])
local table_id = key_id(KEYS[1])

if playerNum == 1 then
    --[[
    	del hash data
    --]]
    redis.call('DEL', KEYS[1])

    --[[
    	remove data index
    --]]
    redis.call('ZREM', table_index, table_id)

    --[[
        remove zset room timedata
    --]]
    redis.call('ZREM', table_time, table_id)

    return cjson.encode(exe_ret)
end


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



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

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

return cjson.encode(exe_ret)



