var express = require('express');
var _ = require('lodash');

var {data, readFiles, writer} = require('../model');

var router = express.Router();

router.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome to fake api!' });   
});

router.get('/:model/:id?', function(req, res) {
  var model = req.params.model;
  var store = data[model];

  console.log(req.originalUrl);
  
  if(req.params.id){
    let index = _.findIndex(store, function(o) { return o.id == req.params.id; });
    if(index > -1) store = store[index];
    else store = {};
  }
  res.json(store);
});

router.post('/:model/:id?', function(req, res) {
  if (!req.body) return res.sendStatus(400);
  var src = './model/data/' + req.params.model + '.js';

  readFiles(src, function(filename, content) {
    var existing = JSON.parse(content);
    var lastId = existing[existing.length-1].id;

    var newData = req.body;
    newData.id = ++lastId;

    existing.push(newData);

    writer(src, JSON.stringify(existing, null, 2));

    res.json(newData);
  }, function(err) {
    res.json(err);
  });
})

module.exports = router;
@@ -353,16 +353,124 @@
 odel%5D;%0A%0A
+  if(typeof store == 'undefined') res.json(%7B%22error%22: true, %22code%22: 500, %22desc%22: %22internal server error%22%7D);%0A%0A
   consol
@@ -493,16 +493,16 @@
 alUrl);%0A
-
   %0A  if(
@@ -659,16 +659,68 @@
 tore = %7B
+%22error%22: true, %22code%22: 404, %22desc%22: %22data not found%22
 %7D;%0A  %7D%0A 
@@ -836,16 +836,211 @@
 s(400);%0A
+%0A  var model = req.params.model;%0A  var id = req.params.id;%0A  var store = data%5Bmodel%5D;%0A%0A  if(typeof store == 'undefined') res.json(%7B%22error%22: true, %22code%22: 500, %22desc%22: %22internal server error%22%7D);%0A%0A
   var sr
@@ -1061,27 +1061,16 @@
 ata/' + 
-req.params.
 model + 

add error exception