'use strict';

var Reflux = require('reflux');
var StateMixin = require('reflux-state-mixin');
var DeploymentAwarenessStore = require('./index');
var TopologyType = require('../models/topology-type');

/**
 * The default description.
 */
var DEFAULT_DESCRIPTION = 'Topology type not yet discovered.';

/**
 * Read State store.
 */
var ReadStateStore = Reflux.createStore({
  /**
   * adds a state to the store, similar to React.Component's state
   * @see https://github.com/yonatanmn/Super-Simple-Flux#reflux-state-mixin
   *
   * If you call `this.setState({...})` this will cause the store to trigger
   * and push down its state as props to connected components.
   */
  mixins: [StateMixin.store],

  /**
   * Initialize by listening to topology changes.
   */
  init: function init() {
    DeploymentAwarenessStore.listen(this.topologyChanged.bind(this));
  },


  /**
   * Looks at the topology description and determines if Compass is in a
   * readable state.
   *
   * @param {Object} description - The topology description.
   */
  topologyChanged: function topologyChanged(description) {
    var topologyType = description.topologyType;
    var readPreference = global.hadronApp.connection.read_preference;
    var isReadable = TopologyType.isReadable(topologyType, readPreference);
    this.setState({
      isReadable: isReadable,
      description: this._getDescription(isReadable, topologyType, readPreference)
    });
  },


  /**
   * Initialize the Read State store state. The returned object must
   * contain all keys that you might want to modify with this.setState().
   *
   * @return {Object} initial store state.
   */
  getInitialState: function getInitialState() {
    return {
      isReadable: false,
      description: DEFAULT_DESCRIPTION
    };
  },
  _getDescription: function _getDescription(isReadable, topologyType, readPreference) {
    var topology = TopologyType.humanize(topologyType);
    var note = isReadable ? 'is readable' : 'is not readable';
    return 'Topology type ' + topology + ' in conjunction with read preference ' + readPreference + ' ' + note;
  }
});

module.exports = ReadStateStore;