var fs = require('fs-extra');

module.exports = (lib) => {
  lib.trigger.add({
    name: 'clean',
    call: /^\!clean/i,
    level: 100,
    active: 0,
    func: (e) => {
      var dir_b = fs.readdirSync('./b/'); // Items
      var dir_t = fs.readdirSync('./t/'); // Thumbnails
      var items_id = [];
      var items_dest = [];
      var failed_ids = [];
      var failed_dests = [];
      lib.sql.query("select `id`, `dest` from `f0ck`.`items`", (err, rows, fields) => {
        rows.forEach((e,i,a) => {
          items_id.push(e.id+'.png');
          items_dest.push(e.dest);
        });
        dir_b.forEach((e,i,a) => {
          if( items_dest.indexOf('./b/'+e) === -1 && e != '.empty' ) {
            failed_dests.push(e);
            fs.unlink('./b/'+e);
          }
        });
        dir_t.forEach((e,i,a) => {
          if( items_id.indexOf(e) === -1 ) {
            failed_ids.push(e);
            fs.unlink('./t/'+e);
          }
        });
        e.reply('unused thumbnails: ' + failed_ids.length + ' ; unused dests: ' + failed_dests.length);
      }).on('error', (err) => {
        e.reply(err);
      });
    },
    desc: 'testtrigger'
  });
};