var bind = require('lodash.bind');
var flatten = require('lodash.flatten');
var isArray = require('lodash.isarray');
var map = require('lodash.map');
var memoize = require('lodash.memoize');
var toArray = require('lodash.toarray');

var Bacon = require('baconjs');
var Advisor = require('autocrat-advisor');
var onTransitionTo = require('../transition-events').onTransitionTo;
var onTransitionFrom = require('../transition-events').onTransitionFrom;

function computeProvincePatternHash() {
  var selectors = flatten(arguments),
      hash;

  // Don't rely on automatic type conversion. Is this possibly faster?
  selectors = map(selectors, function(pattern){
    return pattern.toString();
  });

  return selectors.join('');
}

var federationAdvisor = new (Advisor.extend({
  name: 'federation'
}));

federationAdvisor.isCurrently = memoize(bind(function() {
  var autocrat = this.autocrat,
      selectors = toArray(arguments),
      stream, federationCallback;

  // Accept either a single array of federation selectors, or
  // variadic arguments
  if(selectors.length === 1 && isArray(selectors[0])) {
    selectors = selectors[0];
  }

  // this.addExpertise('changing', {
  //   change: Advisor.Action,
  // });

  stream = new Bacon.Bus();
  stream.name('federation-isCurrently-' + computeProvincePatternHash(selectors));

  onTransitionTo(autocrat, selectors, bind(stream.push, stream));

  return stream;
}, federationAdvisor), computeProvincePatternHash);


federationAdvisor.wasPreviously = memoize(function(autocrat) {

}, computeProvincePatternHash);


module.exports = federationAdvisor;
