'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Generator = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _yeomanGenerator = require('yeoman-generator');

var _generatorBase = require('../generator-base');

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Generator = exports.Generator = function (_Base) {
  _inherits(Generator, _Base);

  function Generator() {
    var _Object$getPrototypeO;

    _classCallCheck(this, Generator);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    var _this = _possibleConstructorReturn(this, (_Object$getPrototypeO = Object.getPrototypeOf(Generator)).call.apply(_Object$getPrototypeO, [this].concat(args)));

    _this.argument('name', { type: String, required: true });

    _this.option('route', {
      desc: 'URL for the endpoint',
      type: String
    });

    _this.option('models', {
      desc: 'Specify which model(s) to use',
      type: String
    });

    _this.option('endpointDirectory', {
      desc: 'Parent directory for endpoints',
      type: String
    });
    return _this;
  }

  _createClass(Generator, [{
    key: 'initializing',
    value: function initializing() {
      // init shared generator properies and methods
      return (0, _generatorBase.genNamedBase)(this);
    }
  }, {
    key: 'prompting',
    value: function prompting() {
      var _this2 = this;

      var promptCb = function promptCb(props) {
        if (props.route.charAt(0) !== '/') {
          props.route = '/' + props.route;
        }

        _this2.route = props.route;

        if (props.models) {
          delete _this2.filters.mongoose;
          delete _this2.filters.mongooseModels;
          delete _this2.filters.sequelize;
          delete _this2.filters.sequelizeModels;

          _this2.filters[props.models] = true;
          _this2.filters[props.models + 'Models'] = true;
        }
      };

      if (this.options.route) {
        if (this.filters.mongoose && this.filters.sequelize && this.options.models) {
          return promptCb(this.options);
        } else {
          if (this.filters.mongooseModels) this.options.models = 'mongoose';else if (this.filters.sequelizeModels) this.options.models = 'sequelize';else delete this.options.models;
          return promptCb(this.options);
        }
      }

      var name = this.name;

      var base = this.config.get('routesBase') || '/api/';
      if (base.charAt(base.length - 1) !== '/') {
        base = base + '/';
      }

      // pluralization defaults to true for backwards compat
      if (this.config.get('pluralizeRoutes') !== false) {
        name = name + 's';
      }

      var prompts = [{
        name: 'route',
        message: 'What will the url of your endpoint be?',
        default: '' + base + name
      }, {
        type: 'list',
        name: 'models',
        message: 'What would you like to use for the endpoint\'s models?',
        choices: ['Mongoose', 'Sequelize'],
        default: this.filters.sequelizeModels ? 1 : 0,
        filter: function filter(val) {
          return val.toLowerCase();
        },
        when: function when() {
          return _this2.filters.mongoose && _this2.filters.sequelize;
        }
      }];

      return this.prompt(prompts).then(promptCb);
    }
  }, {
    key: 'configuring',
    value: function configuring() {
      this.routeDest = _path2.default.join(this.options.endpointDirectory || this.config.get('endpointDirectory') || 'server/api/', this.name);
    }
  }, {
    key: 'writing',
    value: function writing() {
      this.sourceRoot(_path2.default.join(__dirname, '../../templates/endpoint'));
      this.processDirectory('.', this.routeDest);
    }
  }, {
    key: 'end',
    value: function end() {
      if (this.config.get('insertRoutes')) {
        var routesFile = this.config.get('registerRoutesFile');
        var reqPath = this.relativeRequire(this.routeDest, routesFile);
        var routeConfig = {
          file: routesFile,
          needle: this.config.get('routesNeedle'),
          splicable: ['app.use(\'' + this.route + '\', require(\'' + reqPath + '\'));']
        };
        this.rewriteFile(routeConfig);
      }

      if (this.filters.socketio && this.config.get('insertSockets')) {
        var socketsFile = this.config.get('registerSocketsFile');
        var reqPath = this.relativeRequire(this.routeDest + '/' + this.basename + '.socket', socketsFile);
        var socketConfig = {
          file: socketsFile,
          needle: this.config.get('socketsNeedle'),
          splicable: ['require(\'' + reqPath + '\').register(socket);']
        };
        this.rewriteFile(socketConfig);
      }

      if (this.filters.sequelize && this.config.get('insertModels')) {
        var modelsFile = this.config.get('registerModelsFile');
        var reqPath = this.relativeRequire(this.routeDest + '/' + this.basename + '.model', modelsFile);
        var modelConfig = {
          file: modelsFile,
          needle: this.config.get('modelsNeedle'),
          splicable: ['db.' + this.classedName + ' = db.sequelize.import(\'' + reqPath + '\');']
        };
        this.rewriteFile(modelConfig);
      }
    }
  }]);

  return Generator;
}(_yeomanGenerator.Base);

module.exports = Generator;