/**
 * @file
 * A Backbone Model for the state of Contextual module's edit toolbar tab.
 */

(function (Drupal, Backbone) {

  "use strict";

  /**
   * Models the state of the edit mode toggle.
   */
  Drupal.contextualToolbar.StateModel = Backbone.Model.extend({

    defaults: {
      // Indicates whether the toggle is currently in "view" or "edit" mode.
      isViewing: true,
      // Indicates whether the toggle should be visible or hidden. Automatically
      // calculated, depends on contextualCount.
      isVisible: false,
      // Tracks how many contextual links exist on the page.
      contextualCount: 0,
      // A TabbingContext object as returned by Drupal.TabbingManager: the set
      // of tabbable elements when edit mode is enabled.
      tabbingContext: null
    },


    /**
     * {@inheritdoc}
     *
     * @param Object attrs
     * @param Object options
     *   An object with the following option:
     *     - Backbone.collection contextualCollection: the collection of
     *       Drupal.contextual.StateModel models that represent the contextual
     *       links on the page.
     */
    initialize: function (attrs, options) {
      // Respond to new/removed contextual links.
      this.listenTo(options.contextualCollection, {
        'reset remove add': this.countCountextualLinks,
        'add': this.lockNewContextualLinks
      });

      this.listenTo(this, {
        // Automatically determine visibility.
        'change:contextualCount': this.updateVisibility,
        // Whenever edit mode is toggled, lock all contextual links.
        'change:isViewing': function (model, isViewing) {
          options.contextualCollection.each(function (contextualModel) {
            contextualModel.set('isLocked', !isViewing);
          });
        }
      });
    },

    /**
     * Tracks the number of contextual link models in the collection.
     *
     * @param Drupal.contextual.StateModel contextualModel
     *   The contextual links model that was added or removed.
     * @param Backbone.Collection contextualCollection
     *    The collection of contextual link models.
     */
    countCountextualLinks: function (contextualModel, contextualCollection) {
      this.set('contextualCount', contextualCollection.length);
    },

    /**
     * Lock newly added contextual links if edit mode is enabled.
     *
     * @param Drupal.contextual.StateModel contextualModel
     *   The contextual links model that was added.
     * @param Backbone.Collection contextualCollection
     *    The collection of contextual link models.
     */
    lockNewContextualLinks: function (contextualModel, contextualCollection) {
      if (!this.get('isViewing')) {
        contextualModel.set('isLocked', true);
      }
    },

    /**
     * Automatically updates visibility of the view/edit mode toggle.
     */
    updateVisibility: function () {
      this.set('isVisible', this.get('contextualCount') > 0);
    }

  });

})(Drupal, Backbone);
