'use strict';
var endOfLine = require('os').EOL
  , fs = require('fs')
  , join = require('path').join
  , genBase = require('../genBase');


var Generator = module.exports = genBase.extend();

Generator.prototype.prompting = function prompting() {
  this.askForModuleName({url: true});
};

Generator.prototype.writing = function writing() {
  var config = this.getConfig();

  // load app.js to prepare adding new state
  var filePath = join(this.config.path, '../src/', config.modulePath, config.moduleName + '.js')
    , file = fs.readFileSync(filePath, 'utf8');

  // find line to add new state
  var lines = file.split(endOfLine)
    , lineIndex = 0;
  lines.forEach(function (line, i) {
    if (line.indexOf('controller:') !== -1) {
      lineIndex = i;
    }
  });

  // create new state
  var newState = [
    '    })',
    '    .state(\'' + config.lowerCamel + '\', {',
    '      url: \'/' + this.url + '\',',
    '      templateUrl: \'' + this.module + '/' + config.hyphenName + '.tpl.html\',',
    '      controller: \'' + config.ctrlName + '\'',
  ];

  // insert new state and join all lines
  lines.splice(lineIndex+1, 0, newState.map(function (line) {
    return line;
  }).join(endOfLine));

  // save modifications
  fs.writeFileSync(filePath, lines.join(endOfLine));
};

Generator.prototype.end = function end() {
  this.invoke('ng-poly:controller', {
    args: [this.name],
    options: {
      options: {
        module: this.module
      }
    }
  });
  this.invoke('ng-poly:view', {
    args: [this.name],
    options: {
      options: {
        module: this.module
      }
    }
  });
};
@@ -638,132 +638,726 @@
   , 
-lineIndex = 0;%0A  lines.forEach(function (line, i) %7B%0A    if (line.indexOf('controller:') !== -1) %7B%0A      lineIndex = i;%0A    %7D
+stateStartIndex = -1%0A    , stateEndIndex = -1%0A    , braceCount = 0; // %7B%7D%0A  lines.forEach(function (line, i) %7B%0A    // look for .state and set stateStartIndex%0A    if (line.indexOf('.state(') %3E -1) %7B%0A      stateStartIndex = i;%0A    %7D%0A%0A    // open braces add to braceCount%0A    if (stateStartIndex %3E -1 && line.indexOf('%7B') %3E -1) %7B%0A      braceCount++;%0A    %7D%0A%0A    // close braces subract from braceCount%0A    if (stateStartIndex %3E -1 && line.indexOf('%7D') %3E -1) %7B%0A      braceCount--;%0A    %7D%0A%0A    // when braceCount = 0 the end of the state has been reached%0A    // set stateEndIndex%0A    if (stateStartIndex %3E -1 && braceCount === 0) %7B%0A      stateEndIndex = i;%0A    %7D%0A%0A    // loop through everything to append new route at the end
 %0A  %7D
@@ -1661,43 +1661,77 @@
  // 
-insert new state and join all lines
+join the state%0A  // insert state above %7D); of the original last state
 %0A  l
@@ -1746,19 +1746,21 @@
 ice(
-line
+stateEnd
 Index
-+1
 , 0,

generalize route addition