var fs = require('fs-extra');
var http = require('http');
var https = require('https');
var exec = require('child_process').exec;
var crypto = require('crypto');
var request = require('request');

var self = Lib.prototype;
self.bot = require('coffea')();

self.admins = [];
self.debug = false;
self.trigger = {
  trigger: [],
  chans: {},
  add: (args) => {
    self.trigger.trigger.push({
      name: args.name,
      call: args.call,
      func: args.func,
      desc: args.desc,
      level: args.level,
      active: args.active
    });
  }
};

module.exports = Lib;
function Lib(config) {
  self.config = config;
  self.sql = config.sql;
  self.cfg = config.cfg;
  self.debug = self.cfg.main.debug;
  self.loadIRC();
  self.loadUser((cb) => console.log((cb)?"Admins wurden geladen":"Admins konnten nicht geladen werden"));
  self.loadTrigger();
  self.loadEvents();
}

self.getUserlevel = (user, network, channel, cb) => {
  self.bot.whois(user, network, (err, data) => {
    self.bot.names(channel, network, (names) => {
      var lvl_channel = (data.nick in names)? self.cfg.main.level[ names[data.nick] ] : 0;
      var lvl_db = 0;
      if(data.account in self.admins)
        lvl_db = (self.admins[data.account].network === network)? self.admins[data.account].level : 0;
      cb({
        'channel': lvl_channel,
        'db': lvl_db,
        'level': Math.max(lvl_channel, lvl_db)
      });
    });
  });
};
self.loadUser = (cb) => {
  self.admins = [];
  self.sql.query("select * from `f0ck`.`user`", (err, rows, fields) => {
    rows.forEach(e => {
      self.admins[e.account] = {
        id: e.id,
        account: e.account,
        level: e.level,
        network: e.network
      };
    });
    if(cb) cb(true);
  }).on('error', () => {
    if(cb) cb(false);
  });
}
self.checkRepost = (url, cbcr) => {
  self.sql.query("select count(id) as count, id from `f0ck`.`items` where `src` = ?", url, (err, rows, fields) => {
    cbcr((rows[0].count == 0)?true:rows[0].id);
  });
};
self.checkRepostCheckSum = (cs, cbcrcs) => {
  self.sql.query("select count(id) as count, id from `f0ck`.`items` where `checksum` = ?", cs, (err, rows, fields) => {
    cbcrcs((rows[0].count == 0)?true:rows[0].id);
  });
};
self.formatSize = (size) => {
  var i = Math.floor(Math.log(size) / Math.log(1024));
  return (size / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + ['B', 'kB', 'MB', 'GB', 'TB'][i];
};
self.getCheckSum = (file, cbcs) => {
  var sha256sum = crypto.createHash('sha256');
  fs.ReadStream(file)
    .on('data', d => sha256sum.update(d))
    .on('end', () => cbcs(sha256sum.digest('hex')));
};
self.generateThumbs = () => {
  var outdir = './t';
  self.sql.query("select * from `f0ck`.`items`", (err, rows, fields) => {
    rows.forEach((e,i,a) => {
      var thumbnail = outdir+'/'+e.id+'.png';
      if(!fs.existsSync(thumbnail)) {
        //if(e.thumb == '') {
          var cmd;
          switch(e.mime) {
            case "video/mp4":
            case "video/webm":
            case "video/quicktime":
            case "audio/mpeg":
            case "audio/ogg":
            case "audio/flac":
            case "audio/x-flac":
            case "image/gif":
              exec('ffmpegthumbnailer -i'+e.dest+' -s1024 -o'+thumbnail, (error) => {
                if(error) {
                  self.log('failed thumbnail for '+e.id+' ('+e.mime+')');
                    if(e.mime.match(/audio/i))
                      fs.copySync('./s/mp3.png', thumbnail); // copy standardthumbnail
                    else
                      fs.copySync('./s/f0ck.png', thumbnail);
                }
                else
                  exec('convert '+thumbnail+' -resize "128x128^" -gravity center -crop 128x128+0+0 +repage '+thumbnail, (error) => {
                    if(error) console.log(error);
                    self.log((error?'failed':'generated') + ' thumbnail for '+e.id+' ('+e.mime+')');
                  });
              });
              break;
            case "image/png":
            case "image/jpeg":
              exec('convert '+e.dest+' -resize "200x200^" -gravity center -crop 128x128+0+0 +repage '+thumbnail, (error) => {
                if(error) console.log(error);
                self.log((error)?'failed thumbnail for '+e.id+' ('+e.mime+')':'generated thumbnail for '+e.id+' ('+e.mime+')');
              });
              break;
          }
        /*}
        else {
          var dat = fs.createWriteStream(thumbnail);
          request(e.thumb).pipe(dat);
          dat.on('finish', () => {
            dat.close();
            exec('convert '+thumbnail+' -resize "200x200^" -gravity center -crop 128x128+0+0 +repage '+thumbnail, (error) => {
              if(error) console.log(error);
              self.log((error)?'failed thumbnail for '+e.id+' ('+e.mime+')':'generated thumbnail for '+e.id+' ('+e.mime+')');
            });
          });
        }*/
      }
    });
  });
};
self.log = (msg) => {
  if(self.debug)
    self.bot.send(self.cfg.main.debugchannel, msg, self.cfg.main.debugnetwork);
};
self.loadTrigger = () => {
  var files = fs.readdirSync(__dirname+'/trigger/');
  files.forEach((file) => {
    if(file.substr(-3, 3) === '.js') {
      console.log('Loading trigger', file);
      require(__dirname+'/trigger/' + file)(self);
    }
  });
};
self.loadEvents = () => {
  var files = fs.readdirSync(__dirname+'/events/');
  files.forEach((file) => {
    if(file.substr(-3, 3) === '.js') {
      console.log('Loading event', file);
      require(__dirname+'/events/' + file)(self);
    }
  });
};
self.groupUserModes = modes => {
  var modesToApply = [], currentPrefix, queuedModes;
  while(modes.length) {
    queuedModes = "";
    currentPrefix = modes[0][0];
    modes.some(mode => {
      if(mode[0] === currentPrefix) queuedModes += mode[1];
      else return true;
    });
    modesToApply.push(currentPrefix + queuedModes);
    for(var i = 0; i < queuedModes.length; i++) modes.shift();
  }
  return modesToApply;
};
self.userModeDiff = (h, q) => {
  var ret = [], index;
  while(h.length && q.length) {
    if((index = q.indexOf(h[h.length - 1])) !== -1)
      q = q.slice(0, index) + q.slice(index + 1);
    else
      ret.push('-' + h[h.length - 1]);
    h = h.slice(0, -1);
  }
  var sign = q.length ? '+' : '-';
  if(!q.length) q = h;
  if(index = q.length)
    while(index--)
      ret.push(sign + q[index]);
  return ret;
};
self.modesToString = modes => {
  var modeStr = "";
  modes.forEach(entry => {
    if(entry === "~")
      modeStr += "q";
    else if(entry === "&")
      modeStr += "a";
    else if(entry === "@")
      modeStr += "o";
    else if(entry === "%")
      modeStr += "h";
    else if(entry === "+")
      modeStr += "v";
  });
  return modeStr;
};
self.levelToModes = level => {
  if(level >= 70)
    return "ao";
  if(level >= 60)
    return "o";
  if(level >= 50)
    return "h";
  if(level >= 10)
    return "v";
  return "";
};

self.loadIRC = () => {
  self.cfg.irc.irccfg.forEach(e => {
    self.bot.add({
      "name": e.name,
      "host": e.host,
      "port": e.port,
      "ssl": e.ssl,
      "ssl_allow_invalid": e.ssl_allow_invalid,
      "pass": e.pass,
      "nick": e.nick,
      "username": e.username,
      "realname": e.realname,
      "channels": e.channels || [],
      "throttling": e.throttling
    });
    console.log("Server "+e.name+" wurde geladen");
  });
};

self.genStdTrigger = () => {
  var out = {};
  self.trigger.trigger.forEach((entry, key) => {
    out[entry.name] = entry.active?true:false;
  });
  return out;
};
