


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 function getNewX(point, dir)
    local pt = tonumber(point)
    local d = tonumber(dir)
    if d == 2 then
        pt = point + 1
    elseif d == 4 then
        pt = point - 1
    end
    return pt
end

local function getNewY(point, dir)
    local pt = tonumber(point)
    local d = tonumber(dir)
    if d == 1 then
        pt = point + 1
    elseif d == 3 then
        pt = point - 1
    end
    return pt
end




local result        = {}
local matchId       = ARGV[1]
local playerId      = ARGV[2]
local direction     = ARGV[3]

local headPositions  = redis.call("LRANGE","BATTLES:POSITION:{"..matchId.."}:"..playerId,0,0)
local headPos        = split(headPositions[1], ':')
local getX           = getNewX(headPos[1], direction)
local getY           = getNewY(headPos[2], direction)
local rows           = redis.call("HGET", "BATTLES:MATCH:{"..matchId.."}", "ROWS")
local coloumns       = redis.call("HGET", "BATTLES:MATCH:{"..matchId.."}", "COLOUMNS")

if tonumber(getX) >= tonumber(coloumns) then
    getX = 0
end
if tonumber(getY) >= tonumber(rows) then
    getY = 0
end

if tonumber(getX) < 0 then
    getX = tonumber(coloumns) - 1
end
if tonumber(getY) < 0 then
    getY = tonumber(rows) - 1
end

local newPos         = redis.call("HGET", "BATTLES:MATCH:{"..matchId.."}", "MAP"..getX..":"..getY)
local speed          = redis.call("HGET", "BATTLES:MATCH:{"..matchId.."}:"..playerId, "speed")
local score          = redis.call("HGET", "BATTLES:MATCH:{"..matchId.."}:"..playerId, "score")
local length         = redis.call("LLEN", "BATTLES:POSITION:{"..matchId.."}:"..playerId)
local foodEatenCont  = redis.call("HGET", "BATTLES:MATCH:{"..matchId.."}:"..playerId, "foodContinousCount")

table.insert(result, newPos)
table.insert(result, getX)
table.insert(result, getY)
table.insert(result, speed)
table.insert(result, score)
table.insert(result, length)
table.insert(result, foodEatenCont)

return result
