/**
 * Copyright (c) 2015 Alex Grant (@localnerve), LocalNerve LLC
 * Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms.
 */
'use strict';

var debug = require('debug')('Example:Data:Cache');
var markdown = require('./markdown');

// FIXME: 
// Cache storage should not be in this process
// in a real application (issue #9)
var cache = {};

function writeToCache (params, data) {  
  var obj = {
    models: params.models,
    data: data    
  };
  cache[params.resource] = obj;

  debug('wrote cache[' + params.resource + '] = '+require('util').inspect(obj, { depth: null }));
}

var formatToCache = {
  markup: function (params, data) {    
    writeToCache(params, data);
  },
  markdown: function (params, data) {
    writeToCache(params, markdown(data));
  },
  json: function (params, data) {
    var obj = JSON.parse(data);
    Object.keys(obj).forEach(function(key) {
      writeToCache({
        resource: key
      }, obj[key]);
    });
  }
};

function readFromCache (cached) {
  var result = {
    models: cached.models,
    data: cached.data
  };

  if (cached.models) {
    result.models = cached.models.reduce(function(prev, curr) {
      prev[curr] = cache.models.data[curr];
      return prev;
    }, {});
  }

  debug('result', require('util').inspect(result, { depth: null}));
  return result;
}

module.exports = {
  get: function (resource) {
    var result;
    var cached = cache[resource];

    if (cached) {      
      result = readFromCache(cached);
      // TODO: support returning formatted cached result
      result = result.data;
    }

    return result;
  },

  put: function (params, data) {
    debug('putting data into cache', 'resource: '+params.resource, 'format: '+params.format, 'data: '+data);

    if (!params || !params.resource || !data) {
      throw new Error('Invalid arguments to cache put');
    }

    formatToCache[params.format || 'json'](params, data);
  }
};
@@ -270,17 +270,16 @@
 / FIXME:
- 
 %0A// Cach
@@ -409,18 +409,16 @@
  data) %7B
-  
 %0A  var o
@@ -465,20 +465,16 @@
 ta: data
-    
 %0A  %7D;%0A  
@@ -553,13 +553,11 @@
 + '%5D
- = '+
+', 
 requ
@@ -660,20 +660,16 @@
  data) %7B
-    
 %0A    wri
@@ -1257,20 +1257,29 @@
 ebug('re
-sult
+ad from cache
 ', requi
@@ -1459,22 +1459,16 @@
 ached) %7B
-      
 %0A      r
@@ -1926,16 +1926,17 @@
 s, data);%0A  %7D%0A%7D;
+%0A

clean up code