import fs from 'fs';
import debug from 'debug';
import path from 'path';
import env2obj from 'env2obj';
import _ from 'lodash';
const log = debug('helper:config:info');
const error = debug('helper:config:error');
const debg = debug('helper:config:debug');

export class Config {
  /**
   * Create a config.
   * @param {String} basedir path of config file - default = PWD
   * @param {prefix} prefix - of env config variables
   * e.g. APP_TITLE="hi" will be config.title
   */
  constructor(basedir = process.env.PWD, prefix = 'APP') {
    let env = process.env.NODE_ENV || 'development';
    process.env.NODE_ENV = env;
    /**
    *@object
    *the file config.js
    */
    this.file = {};
    if (fs.existsSync(path.join(basedir, 'config.js'))) {
      this.file = require(path.join(basedir, 'config.js'), 'utf-8')[env];
    } else {
      debg('file', 'did not use ', path.join(basedir, 'config.js'))
    }
    /**
    the config.default.js config
    @object
    */
    this.fileDefault = {};
    if (fs.existsSync(path.join(basedir, 'config.default.js'))) {
      this.fileDefault =
          require(path.join(basedir, 'config.default.js'), 'utf-8')[env]
    } else {
      debg('file', 'did not use ', path.join(basedir, 'config.default.js'))
    }
    /**
    *@object
    *the config.env config
    */
    this.env = env2obj(prefix);
    this.config = _.merge(this.fileDefault, this.file, this.env);
    // todo: lowwercase every key
    debg('used config', this.config)
  }
}
/**
default config loaded with PWD,APP
*/
const config = new Config();

exports.default = config.config;