'use strict';

import * as Redis from 'ioredis';
import Util from './util';

const MONTH_IN_SECONDS = 2592000;

// all methods return Promises
export default class RedisStore {
  private _client: Redis.Redis;

  constructor (redisUrl) {
    this._client = new Redis(redisUrl);
  }

  add (key: string, value: Object) {
    value = JSON.stringify(value);
    return this._client.setex(key, MONTH_IN_SECONDS, value)
            .catch(Util._promiseErrorHandler);
  }

  hAdd (hash, key, value) {
    return this._client.hset(hash, key, value).catch(Util._promiseErrorHandler);
  }

  remove (key) {
    return this._client.del(key).catch(Util._promiseErrorHandler);
  }

  hRemove (hash, key) {
    return this._client.hdel(hash, key).catch(Util._promiseErrorHandler);
  }

  get (key) {
    return this._client.get(key).then(JSON.parse).catch(Util._promiseErrorHandler);
  }

  hGet (hash, key) {
    return this._client.hget(hash, key).catch(Util._promiseErrorHandler);
  }

  hGetAll (hash) {
    return this._client.hgetall(hash).catch(Util._promiseErrorHandler);
  }

  hKeys (hash) {
    return this._client.hkeys(hash).catch(Util._promiseErrorHandler);
  }

  exists (key) {
    return this._client.exists(key).catch(Util._promiseErrorHandler);
  }

  hExists (hash, key) {
    return this._client.hexists(hash, key).catch(Util._promiseErrorHandler);
  }

  get isConnected (): boolean {
    return this._client.status === 'ready';
  }
}
