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 coloumns      = tonumber(ARGV[4])
local rows          = tonumber(ARGV[5])
local opponentPlayerId = ARGV[6]
local clientNewPosX = tonumber(ARGV[7])
local clientNewPosY = tonumber(ARGV[8])

local curPositionX   = tonumber(redis.call("HGET", "BATTLES:MATCH:{" .. matchId .. "}:" .. playerId, "playerX"))
local curPositionY   = tonumber(redis.call("HGET", "BATTLES:MATCH:{" .. matchId .. "}:" .. playerId, "playerY"))

local opponentPosX   = tonumber(redis.call("HGET", "BATTLES:MATCH:{" .. matchId .. "}:" .. opponentPlayerId, "playerX"))
local opponentPosY   = tonumber(redis.call("HGET", "BATTLES:MATCH:{" .. matchId .. "}:" .. opponentPlayerId, "playerY"))

local isFreezed      = tonumber(redis.call("HGET", "BATTLES:MATCH:{" .. matchId .. "}:" .. playerId, "STATE"))

local newPositionX   = getNewX(curPositionX, direction)
local newPositionY   = getNewY(curPositionY, direction)

if(newPositionX >= coloumns or newPositionX < 0 or newPositionY >= rows or newPositionY < 0 or 
    (newPositionX == opponentPosX and newPositionY == opponentPosY) 
     or (newPositionX ~= clientNewPosX or newPositionY ~= clientNewPosY)
     or isFreezed == 1) then
    table.insert(result, 0)         --move possible
else
    table.insert(result, 1)         --move possible
end

table.insert(result, newPositionX)  --new pos
table.insert(result, newPositionY)  --new pos

local npc            = redis.call("HGET", "BATTLES:MATCH:{" .. matchId .. "}:row:" .. newPositionY, "map:" .. newPositionX)
table.insert(result, npc)

local coin          = redis.call("HGET", "BATTLES:MATCH:{" .. matchId .. "}:coins", newPositionY .. ":" .. newPositionX)
table.insert(result, coin)   

table.insert(result, curPositionX)
table.insert(result, curPositionY)
table.insert(result, opponentPosX)
table.insert(result, opponentPosY)
return result
