'use strict';

/**
 * Module dependencies
 */

// Node.js core.
const fs = require('fs');
const path = require('path');

// Public node modules.
const _ = require('lodash');

/**
 * Expose main routes of the generated API
 */

module.exports = scope => {
  function generateRoutes() {
    return {
      routes: [{
        method: 'GET',
        path: '/' + (scope.humanizeSubId || scope.humanizeId),
        handler: scope.globalID + '.find',
        config: {
          policies: []
        }
      }, {
        method: 'GET',
        path: '/' + (scope.humanizeSubId || scope.humanizeId) + '/:id',
        handler: scope.globalID + '.findOne',
        config: {
          policies: []
        }
      }, {
        method: 'POST',
        path: '/' + (scope.humanizeSubId || scope.humanizeId),
        handler: scope.globalID + '.create',
        config: {
          policies: []
        }
      }, {
        method: 'PUT',
        path: '/' + (scope.humanizeSubId || scope.humanizeId) + '/:id',
        handler: scope.globalID + '.update',
        config: {
          policies: []
        }
      }, {
        method: 'DELETE',
        path: '/' + (scope.humanizeSubId || scope.humanizeId) + '/:id',
        handler: scope.globalID + '.destroy',
        config: {
          policies: []
        }
      }]
    };
  }

  // We have to delete current file
  if (!_.isEmpty(scope.subId)) {
    const current = require(scope.rootPath);

    try {
      // Remove current routes.json
      fs.unlinkSync(scope.rootPath);
      // Merge both array of routes
      current.routes = _.concat(generateRoutes().routes, current.routes);

      return current;
    } catch (e) {
      console.error(e);
      return;
    }
  }

  return generateRoutes();
};

@@ -1387,21 +1387,79 @@
 ) %7B%0A    
-const
+let current;%0A%0A    try %7B%0A      // Copy current routes.json%0A     
  current
@@ -1487,26 +1487,16 @@
 Path);%0A%0A
-    try %7B%0A
       //
@@ -1560,16 +1560,173 @@
 tPath);%0A
+    %7D catch (e) %7B%0A      // Fake existing routes%0A      current = %7B%0A        routes: %5B%5D%0A      %7D;%0A    %7D%0A%0A    try %7B%0A      const newest = generateRoutes().routes;%0A
       //
@@ -1756,31 +1756,68 @@
 utes
+, and remove identical routes
 %0A      
+_.set(
 current
-.
+, '
 routes
- =
+',
  _.c
@@ -1826,47 +1826,68 @@
 cat(
-generateRoutes().routes, current.routes
+newest, _.differenceWith(current.routes, newest, _.isEqual))
 );%0A%0A

Remove identical routes