'use strict';

var Command   = require('../models/command');
var Promise   = require('../ext/promise');
var Blueprint = require('../models/blueprint');
var merge     = require('lodash/object/merge');

var SilentError = require('silent-error');

module.exports = Command.extend({
  name: 'destroy',
  description: 'Destroys code generated by `generate` command.',
  aliases: ['d'],
  works: 'insideProject',

  availableOptions: [
    { name: 'dry-run', type: Boolean, default: false, aliases: ['d'] },
    { name: 'verbose', type: Boolean, default: false, aliases: ['v'] },
    { name: 'pod', type: Boolean, default: false, aliases: ['p'] },
    { name: 'in-repo-addon', type: String, default: null, aliases: ['in-repo', 'ir']}
  ],

  anonymousOptions: [
    '<blueprint>'
  ],

  beforeRun: function(rawArgs){
    try {
    // merge in blueprint availableOptions
      this.registerOptions(this.lookupBlueprint(rawArgs[0]));
    } catch(e) {
      SilentError.debugOrThrow('ember-cli/commands/destroy', e);
    }
  },

  run: function(commandOptions, rawArgs) {
    var blueprintName = rawArgs[0];
    var entityName    = rawArgs[1];

    if (!blueprintName) {
      return Promise.reject(new SilentError('The `' + this.cli.name + ' destroy` command requires a ' +
                                            'blueprint name to be specified. ' +
                                            'For more details, use `' + this.cli.name + ' help`.'));
    }

    if (!entityName) {
      return Promise.reject(new SilentError('The `' + this.cli.name + ' destroy` command requires an ' +
                                            'entity name to be specified. ' +
                                            'For more details, use `' + this.cli.name + ' help`.'));
    }

    var Task = this.tasks.DestroyFromBlueprint;
    var task = new Task({
      ui: this.ui,
      analytics: this.analytics,
      project: this.project,
      settings: this.settings
    });

    var taskArgs = {
      args: rawArgs
    };

    if(this.settings && this.settings.usePods) {
      commandOptions.pod = !commandOptions.pod;
    }

    var taskOptions = merge(taskArgs, commandOptions || {});

    if (this.project.initializeAddons) {
      this.project.initializeAddons();
    }

    return task.run(taskOptions);
  },

  lookupBlueprint: function(name) {
    return Blueprint.lookup(name, {
      paths: this.project.blueprintLookupPaths()
    });
  },

  printDetailedHelp: function() {
    var ui = this.ui;

    ui.writeLine('');
    ui.writeLine('  Run `' + this.cli.name + ' help generate` to view a list of available blueprints.');
  }
});
