import makeDebug from 'debug';
import fp from 'mostly-func';
import { getItems } from 'feathers-hooks-common';

const debug = makeDebug('mostly:feathers-mongoose:hooks:cache');

const defaultOptions = {
  idField: 'id',
  max: 100,
  maxAge: 1000 * 60 * 60
};


export default function (cacheMap, opts) {
  opts = Object.assign({}, defaultOptions, opts);
  
  return context => {
    const idName = opts.idField || (context.service || {}).id;

    let items = getItems(context);
    items = Array.isArray(items) ? items : [items];

    if (context.type === 'after') {
      if (context.method === 'remove') return;

      items.forEach(item => {
        debug('>>> set cache', item[idName]);
        cacheMap.set(item[idName], fp.clone(item));
      });

      return;
    }

    switch (context.method) {
      case 'find': // fall through
      case 'create':
        return;
      case 'get':
        const value = cacheMap.get(context.id);
        debug('<< get cache', context.id, value);
        if (value) {
          context.result = value;
        }
        return context;
      default: // update, patch, remove
        if (context.id) {
          cacheMap.delete(context.id);
          return;
        }

        items.forEach(item => {
          cacheMap.delete(item[idName]);
        });
    }
  };
}
@@ -217,45 +217,8 @@
 d',%0A
-  max: 100,%0A  maxAge: 1000 * 60 * 60%0A
 %7D;%0A%0A
@@ -399,17 +399,66 @@
 %7B%7D).id;%0A
+    const svcName = (context.service %7C%7C %7B%7D).name;
 %0A
-
     let 
@@ -669,12 +669,30 @@
 bug(
-'%3E%3E%3E
+%60%3E%3E $%7BsvcName%7D service
  set
@@ -701,23 +701,21 @@
 ache
-', item%5BidName%5D
+%60, context.id
 );%0A 
@@ -957,32 +957,55 @@
 et(context.id);%0A
+        if (value) %7B%0A  
         debug('%3C
@@ -1006,11 +1006,30 @@
 bug(
-'
+%60
 %3C%3C
+ $%7BsvcName%7D service
  get
@@ -1034,17 +1034,17 @@
 et cache
-'
+%60
 , contex
@@ -1051,38 +1051,10 @@
 t.id
-, value);%0A        if (value) %7B
+);
 %0A   

update debug message of cache