var _ = require('underscore');
var Bacon = require('baconjs');
var Advisor = require('autocrat-advisor');

function streamForRoute(action) {
  return Advisor.Stream(function(baseStream, helpers) {
    return baseStream
      .merge(
        this.autocrat.advisors.route.navigates
        .filter(_.partial(helpers.isPersonRoute, action)
      )
    );
  })
}

module.exports = Advisor.extend({

  name: 'person',

  initialize: function(advisors, wards) {
    this.collection = wards.people;
  },

  helpers: {
    isPersonRoute: function(personAction, advisorEvent){
      var routeName = advisorEvent.data.current.name;
      return routeName.toLowerCase() === ('person' + personAction).toLowerCase();
    }
  },

  viewing: {
    view: Advisor.Action,
    isViewing: streamForRoute('view')
  },

  adding: {
    add: Advisor.Action,
    isAdding: streamForRoute('add')
  },

  editing: {
    edit: Advisor.Action,
    isEditing: streamForRoute('edit')
  },

  creating: {

    create: Advisor.WrapperAction(function() {
      return {
        wrapMethod: [this.collection, 'create'],
        extractData: function(collection, methodRetVal, methodArgs, baseStream){
          return methodRetVal;
        }
      };
    }),

    creates: Advisor.Stream,

    hasCreated: Advisor.Stream(function(baseStream, helpers, customStream) {
      var stream = new Bacon.Bus(),
          advisorName = this.name;

      var pushEvent = function(model, response){
        stream.push(new Advisor.Event(advisorName, 'created', response));
      };

      this.streams.creates.onValue(this.collection, 'once', 'sync', pushEvent);

      return stream;
    }),

    isCreating: Advisor.Stream(function(baseStream) {
      return baseStream.awaiting(this.streams.hasCreated);
    })

  }

});
