'use strict';

var _typeof2 = require('babel-runtime/helpers/typeof');

var _typeof3 = _interopRequireDefault(_typeof2);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/* eslint no-console: 0 */

var path = require('path');
var appRoot = require('app-root-path');
var Listr = require('listr');
var cosmiconfig = require('cosmiconfig');

var packageJson = require(appRoot.resolve('package.json')); // eslint-disable-line
var cgf = require('./changedGitFiles');
var runScript = require('./runScript');
var generateTasks = require('./generateTasks');

// Force colors for packages that depend on https://www.npmjs.com/package/supports-color
// but do this only in TTY mode
if (process.stdout.isTTY) {
  process.env.FORCE_COLOR = true;
}

cosmiconfig('track-changed', {
  rc: '.trackchangedrc',
  rcExtensions: true
}).then(function (result) {
  // result.config is the parsed configuration object
  // result.filepath is the path to the config file that was found
  var config = result.config;
  var verbose = config.verbose;
  // Output config in verbose mode

  if (verbose) console.log(config);
  var concurrent = typeof config.concurrent !== 'undefined' ? config.concurrent : true;
  var renderer = verbose ? 'verbose' : 'update';
  var gitDir = config.gitDir ? path.resolve(config.gitDir) : process.cwd();

  try {
    var _ret = function () {
      var files = cgf(process.argv[2]);
      if (!files || files.length === 0) {
        return {
          v: void 0
        };
      }

      var resolvedFiles = {};
      files.forEach(function (file) {
        var absolute = path.resolve(gitDir, file);
        var relative = path.relative(gitDir, absolute);
        resolvedFiles[relative] = absolute;
      });

      var tasks = generateTasks(config, resolvedFiles).map(function (_task) {
        return {
          title: 'Running tasks for ' + _task.pattern,
          task: function task() {
            return new Listr(runScript(_task.commands, _task.fileList, packageJson, { gitDir: gitDir, verbose: verbose }));
          }
        };
      });

      if (tasks.length) {
        new Listr(tasks, { concurrent: concurrent, renderer: renderer }).run().catch(function (error) {
          console.error(error.message);
          process.exit(1);
        });
      }
    }();

    if ((typeof _ret === 'undefined' ? 'undefined' : (0, _typeof3.default)(_ret)) === "object") return _ret.v;
  } catch (err) {
    console.error(err);
  }
}).catch(function (parsingError) {
  console.error('Could not parse track-changed config.\nMake sure you have created it. See https://github.com/morhetz/track-changed#readme.\n\n' + parsingError + '\n');
  process.exit(1);
});