-- KEYS: [1]orderedSet key [2]elemMap key
-- ARGV: [1]newRealElem [2]elem [3]score [4]maxRank [5] addNew [6] returnRank

local oldRealElem = redis.call("HGET", KEYS[2], ARGV[2])
if oldRealElem then
    if ARGV[5] == "1" then
        return -1
    else
        redis.call("ZREM", KEYS[1], oldRealElem)
    end
end

redis.call("HSET", KEYS[2], ARGV[2], ARGV[1])
redis.call("ZADD", KEYS[1], ARGV[3], ARGV[1])

local newRank = 0
if ARGV[6] == "1" then
    newRank = redis.call("ZRANK", KEYS[1], ARGV[1]) + 1
end

if ARGV[4] ~= "0" then
    redis.call("ZREMRANGEBYRANK", KEYS[1], ARGV[4], -1)
end

return newRank
