
local function split(inputstr, sep)
    if sep == nil then
        sep = "%s"
    end
    local t={} ; local i=1
    for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
        t[i] = str
        i = i + 1
    end
    return t
end

local result        = {}
local matchId       = ARGV[1]
local gameTime      = tonumber(ARGV[2])
local curTime       = tonumber(ARGV[3])
local reviveTime    = tonumber(ARGV[4])
local maxColoumns   = tonumber(ARGV[5])
local gameOverState = tonumber(ARGV[6])

local gameStartTime = tonumber(redis.call("HGET", "BATTLES:MATCH:{" .. matchId .. "}", "STARTTIME"))

if curTime - gameStartTime >= gameTime then
    table.insert(result, 1)             -- game over
    redis.call("HSET", "BATTLES:MATCH:{" .. matchId .. "}", "STATE", gameOverState)
else
    table.insert(result, 0)             -- game not over
end

local playerADead = tonumber(redis.call("HGET", "BATTLES:MATCH:{" .. matchId .. "}:1", "STATE"))
local playerADeadTime = tonumber(redis.call("HGET", "BATTLES:MATCH:{" .. matchId .. "}:1", "DEADTIME"))
local playerBDead = tonumber(redis.call("HGET", "BATTLES:MATCH:{" .. matchId .. "}:2", "STATE"))
local playerBDeadTime = tonumber(redis.call("HGET", "BATTLES:MATCH:{" .. matchId .. "}:2", "DEADTIME"))

if(playerADead == 1) then
    table.insert(result, 1)             -- player A dead
    if(curTime - playerADeadTime >= reviveTime) then
        table.insert(result, 1)         -- revive player A
    else
        table.insert(result, 0)         -- revive player A
    end
else
    table.insert(result, 0)             -- player A dead
    table.insert(result, 0)             -- revive player A
end

if(playerBDead == 1) then
    table.insert(result, 1)             -- player B dead
    if(curTime - playerBDeadTime >= reviveTime) then
        table.insert(result, 1)         -- revive player B
    else
        table.insert(result, 0)         -- revivie player B
    end
else
    table.insert(result, 0)             -- player B dead
    table.insert(result, 0)             -- revive player B 
end

local coinSpawnMap = redis.call("HGETALL", "BATTLES:MATCH:{" .. matchId .. "}:COINS_SPAWN")

local coinRes = {}
math.randomseed(curTime)
for index = 1, #coinSpawnMap, 2 do
    local cp = {}
    local key = split(coinSpawnMap[index], "_")[1]
    local values = coinSpawnMap[index + 1]
    local lstVal = split(values, "_")
    local timeStamp = lstVal[1]
    local randTime = lstVal[2]
    
    table.insert(cp, key)
    if(curTime - tonumber(timeStamp) >= tonumber(randTime)) then
        local coinVal = 1
        local point = 0
        while coinVal == 1 do
            point = math.random(0, maxColoumns)
            coinVal = tonumber(redis.call("HGET", "BATTLES:MATCH:{" .. matchId .. "}:coins", key .. ":" .. point))
        end
        redis.call("HDEL", "BATTLES:MATCH:{" .. matchId .. "}:COINS_SPAWN", coinSpawnMap[index])
        table.insert(cp, point)
        table.insert(coinRes, cp)
    end
end
 table.insert(result, coinRes)
return result