'use strict';

const path = require('path');
const parsePath = require('parse-filepath');

const async = require('async');
const Bluebird = require('bluebird');
const dir = require('node-dir');

function Tasks(pluginDir, tasks) {
  const self = this;

  self.sshDir = path.join(pluginDir, tasks || 'ssh');
  self.files = [];

  dir.files(self.sshDir, (err, files) => {
    if (err) {
      throw err;
    }

    self.files = files;
  });

  self.ssh = function ssh(conn) {
    const result = {};

    return Bluebird.each(self.files, (filePath) => {
      const parse = parsePath(filePath);

      if (parse.ext === '.js' || parse.extname === '.js') {
        return Bluebird.fromCallback((cb) => {
          require(filePath)(conn)(cb);
        }).then((data) => {
          const fileName = parse.name.toLowerCase();
          result[fileName] = data;
        });
      }
    }).return(result);

        /* return new Bluebird(function (resolve, reject) {
            var tasks = {};

            self.files.forEach(function (filePath, i) {
                var parse = parsePath(filePath);

                if (parse.ext === '.js' || parse.extname === '.js') {
                    var fileName = parse.name.toLowerCase();
                    tasks[fileName] = require(filePath)(conn);
                }
            });

            async.series(tasks, function (err, results) {
                conn.end();

                if (err) {
                    reject(err);
                } else {
                    resolve(results);
                }
            });
        });*/
  };

  self.tasks = function tasks() {
    const self = this;
    const args = arguments;

    return new Bluebird((resolve, reject) => {
      const tasks = {};

      self.files.forEach((filePath) => {
        const parse = parsePath(filePath);

        if (parse.ext === '.js' || parse.extname === '.js') {
          const fileName = parse.name.toLowerCase();
          const func = require(filePath);
          tasks[fileName] = func.apply(self, args);
        }
      });

      async.series(tasks, (err, results) => {
        if (err) {
          reject(err);
        } else {
          resolve(results);
        }
      });
    });
  };

  return self;
}

module.exports = Tasks;
