var { createClient } = require('redis');

var client = null;
var connecting = null;

async function getRedis() {
  var url = process.env.REDIS_URL;
  if (!url) return null;
  if (client && client.isOpen) return client;
  if (connecting) return connecting;
  client = createClient({ url: url });
  client.on('error', function(err) {
    console.warn('[redis]', err.message);
  });
  connecting = client.connect().then(function() {
    connecting = null;
    return client;
  }).catch(function(err) {
    connecting = null;
    console.warn('[redis] unavailable:', err.message);
    return null;
  });
  return connecting;
}

async function getJson(key) {
  var redis = await getRedis();
  if (!redis) return null;
  var value = await redis.get(key);
  if (!value) return null;
  try { return JSON.parse(value); } catch (e) { return null; }
}

async function setJson(key, value, ttlSeconds) {
  var redis = await getRedis();
  if (!redis) return false;
  if (ttlSeconds && Number(ttlSeconds) > 0) {
    await redis.set(key, JSON.stringify(value), { EX: Math.floor(Number(ttlSeconds)) });
  } else {
    await redis.set(key, JSON.stringify(value));
  }
  return true;
}

module.exports = { getRedis, getJson, setJson };
