const System = require("../system");
const redis = require("redis");
const settings = require("../../config/settings");
const bluebird = require("bluebird");
bluebird.promisifyAll(redis);

// const logCtl=System.getObject("web.oplogCtl");
class PublishClient {
  constructor() {
    const redisConfig = settings.redis();
    this.client = redis.createClient({
      host: redisConfig.host,
      port: redisConfig.port,
      password: redisConfig.password,
      db: redisConfig.db,
      retry_strategy: function (options) {
        // if (options.error && options.error.code === 'ECONNREFUSED') {
        //     // End reconnecting on a specific error and flush all commands with
        //     // a individual error
        //     return new Error('The server refused the connection');
        // }
        if (options.total_retry_time > 1000 * 60 * 60) {
          // End reconnecting after a specific timeout and flush all commands
          // with a individual error
          return new Error('Retry time exhausted');
        }
        if (options.attempt > 10) {
          // End reconnecting with built in error
          return 10000;
        }
        // reconnect after
        return Math.min(options.attempt * 100, 3000);
      }
    });

    this.client.on("error", function (err) {
      console.log("Error " + err);
    });
  }

  async publish(channel, msg){
    console.log(channel+":"+msg);
    return this.client.publishAsync(channel, msg);
  }

  async rpush(key, val) {
    return this.client.rpushAsync(key, val);
  }

  async lpush(key, val) {
    return this.client.lpushAsync(key, val);
  }

  async rpop(key) {
    this.client.rpop(key);
  }

  async lpop(key) {
    this.client.lpop(key);
  }
}

module.exports = PublishClient;
