var mysql = require('mysql');

var self = Cfg.prototype;
var haDC = () => {
  self.sql = mysql.createConnection(require('../cfg/mysql.json'));
  self.sql.connect((err) => {
    if(err) setTimeout(haDC, 2000);
  });
  self.sql.on('error', (err) => {
    if(err.code === 'PROTOCOL_CONNECTION_LOST') haDC();
  });
};
haDC();

self.cfg = {};
module.exports = Cfg;
function Cfg() {
  self.read(cfg => self.cfg = cfg);
}

self.read = (cb, kat, key) => {
  // main, websrv, irc
  var out = {
    irc: {},
    main: {},
    websrv: {},
    trigger: {}
  };
  self.sql.query("select * from `f0ck`.`cfg`" + (kat?" where `class` = '"+kat+"'"+(key?" && `key` = '"+key+"'":""):""), (err, rows) => {
    if(err || rows.length < 1)
      cb(err);
    else {
      rows.forEach(e => {
        out[e.class][e.key] = ((type, value) => {
          switch(type) {
            case 'string':
              return value;
            break;
            case 'int':
              return parseInt(value);
            break;
            case 'bool':
              return (value === 'true')?true:false;
            break;
            case 'json':
              return JSON.parse(value);
            break;
          }
        })(e.type, e.value);
      });
      if(cb) cb( key?out[kat][key]:out );
    }
  });
};

self.write = (kat, key, value, type, cb) => {
  if(type === "json")
    value = JSON.stringify(value);

  self.sql.query("select * from `f0ck`.`cfg` where `class` = ? && `key` = ? limit 1", [kat, key], (err, rows) => {
    if(rows.length > 0) {
      self.sql.query("update `f0ck`.`cfg` set `value` = ? where `class` = ? && `key` = ?", [value, kat, key], (err) => {
        self.read(cfg => {
          self.cfg = cfg
          if(cb) cb(err);
        });
      });
    }
    else {
      self.sql.query("insert into `f0ck`.`cfg` (`class`,`key`,`value`,`type`) values (?,?,?,?)", [kat, key, value, type], (err) => {
        self.read(cfg => {
          self.cfg = cfg
          if(cb) cb(err);
        });
      });
    }
  });
};
