'use strict';

const _ = require('lodash');
const async = require('async');
const Joi = require('joi');

const plugins = require('libs/plugins.js');

const schema = Joi.object().keys({
  accounts: Joi.array().items(Joi.object().keys({
    id: Joi.string(),
    key: Joi.boolean(),
    privkey: Joi.string().empty(''),
    login: Joi.string(),
    method: Joi.string().required().valid('ssh', 'wmi', 'scanner'),
    password: Joi.string().empty(''),
    enable_password: Joi.string().empty(''),
    port: Joi.number(),
  })).required().min(1),
  ips: Joi.array().items(Joi.string()),
}).options({ allowUnknown: true });

function run(options, done) {
  schema.validate(options, (err, options) => {
    if (err) {
      return done(err);
    }

    let accounts = options.ips.map((ip) => options.accounts.map((account) => {
      const acc = {
        id: account.id,
        username: account.login,
        method: account.method,
        host: ip,
      };

      if (!_.isEmpty(account.password)) {
        acc.password = account.password;
      }

      if (!_.isEmpty(account.enable_password)) {
        acc.enable_password = account.enable_password;
      }

      if (!_.isEmpty(account.port)) {
        acc.port = account.port;
      }

      if (account.key && !_.isEmpty(account.privkey)) {
        acc.privateKey = account.privkey;
      }

      return acc;
    }));

    accounts = _.flatten(accounts);

    let error = null;

    const checkAccount = function (account, result) {
      plugins.run('check-account', account)
                .then(() => {
                  result(true);
                })
                .catch((err) => {
                  error = err;
                  result(false);
                });
    };

    async.filter(accounts, checkAccount, (results) => {
      if (_.isEmpty(results)) {
        done(error || new Error('No valid accounts'));
      } else {
        done(null, results);
      }
    });
  });
}

module.exports.run = run;
