import { Actions } from 'thundercats';
import assign from 'object.assign';
import debugFactory from 'debug';
import Fetchr from 'fetchr';

const debug = debugFactory('freecc:hikes:actions');
const service = new Fetchr({
  xhrPath: '/services'
});

function getCurrentHike(hikes =[{}], dashedName, currentHike) {
  if (!dashedName) {
    return hikes[0];
  }
  const filterRegex = new RegExp(dashedName, 'i');

  return hikes
    .filter(({ dashedName }) => {
      return filterRegex.test(dashedName);
    })
    .reduce((throwAway, hike) => {
      return hike;
    }, currentHike || {});
}

export default Actions({
  // start fetching hikes
  fetchHikes: null,
  // set hikes on store
  setHikes: null
})
  .refs({ displayName: 'HikesActions' })
  .init(({ instance }) => {
    // set up hikes fetching
    instance.fetchHikes.subscribe(
      ({ isPrimed, dashedName }) => {
        if (isPrimed) {
          return instance.setHikes({
            transform: (oldState) => {
              const { hikes, currentContext } = oldState;
              const currentHike = getCurrentHike(
                hikes,
                dashedName,
                currentContext
              );
              return assign({}, oldState, { currentHike });
            }
          });
        }
        service.read('hikes', null, null, (err, hikes) => {
          if (err) {
            debug('an error occurred fetching hikes', err);
          }
          instance.setHikes({
            set: {
              hikes: hikes,
              currentHike: getCurrentHike(hikes, dashedName)
            }
          });
        });
      }
    );
  });

@@ -322,24 +322,52 @@
 shedName) %7B%0A
+    debug('no dashedName');%0A
     return h
@@ -379,16 +379,17 @@
 0%5D;%0A  %7D%0A
+%0A
   const 
@@ -430,16 +430,109 @@
 e, 'i');
+%0A  if (currentHike && filterRegex.test(currentHike.dashedName)) %7B%0A    return currentHike;%0A  %7D
 %0A%0A  retu
@@ -1125,24 +1125,8 @@
 ikes
-, currentContext
  %7D =
@@ -1257,22 +1257,28 @@
     
-currentContext
+oldState.currentHike
 %0A   

return currentHike on load