
(function($, Archibald) {

Drupal.behaviors.archibaldCurricula.hooks.appReady.push(function(app) {
  // Is this one of our apps?
  if (
    typeof app.curriculum === 'undefined' ||
    app.curriculum !== 'lp21'
  ) {
    return;
  }

  var $appWrapper = app.getWrapper(),
      $cyclesValueField = $appWrapper.parents('.form-type-archibald-curricula').find('.archibald-lp21-editor__cycles');

  // Prepare a callback for checking cycles and locking them.
  var checkCycles = function() {
    var activeCycles = [],
        items = app.getItemDatabase().where({
          active: true
        });

    _.each(items, function(item) {
      if (typeof item.get('data').lp21Cycles !== 'undefined') {
        _.each(item.get('data').lp21Cycles, function(cycle) {
          if (activeCycles.indexOf(cycle) === -1) {
            activeCycles.push(cycle);
          }
        });
      }
    });

    // Reset the checkboxes. Uncheck them (unless they were selected by hand)
    // and make sure they are not disabled.
    $appWrapper.find('.archibald-lp21-cycles__cycle input').each(function() {
      var $this = $(this);
      $this.prop({
        checked: $this.hasClass('archibald-lp21-cycles__cycle__input--hand-selected'),
        disabled: false
      });
    });

    // Now, all those that are supposed to be active are to be checked and
    // disabled.
    if (activeCycles.length) {
      _.each(activeCycles, function(cycle) {
        $appWrapper
          .find('.archibald-lp21-cycles__cycle--cycle-' + cycle + ' input')
          .prop({
            checked: true,
            disabled: true
          })
          .change();
      });
    }
  };

  // Add the cycle selector checkboxes, as well as he summary wrapper.
  $appWrapper.find('.archibald-curriculum-ui__editor').after(
    _.template(Archibald.templates.lp21CyclesForm)()
  );
  $appWrapper.find('.archibald-curriculum-ui__summary-wrapper__label').after(
    _.template(Archibald.templates.lp21CyclesSummary)()
  );

  var $summaryCyclesWrapper = $appWrapper.find('.archibald-lp21-summary-cycles');

  // Handle the cycle checkboxes.
  $appWrapper.find('.archibald-lp21-cycles input').change(function() {
    var $this = $(this);

    // Update the summary.
    if ($this.is(':checked')) {
      $summaryCyclesWrapper.addClass('archibald-lp21-summary-cycles--has-cycle-' + this.value);
    }

    // Update the stored values.
    var values = [];
    $appWrapper.find('.archibald-lp21-cycles input:checked').each(function() {
      values.push(this.value);
    });
    $cyclesValueField.val(values.join(','));
  }).click(function() {
    $(this).toggleClass('archibald-lp21-cycles__cycle__input--hand-selected');
  });

  // When an objective is rendered, add a --has-cycle-* modifier class.
  app.on('column:item:render', function(itemModel, itemView, columnCollection, columnView) {
    if (typeof itemModel.get('data').lp21Cycles !== 'undefined') {
      itemView.$el.addClass(itemView.className + '--has-cycles-' + itemModel.get('data').lp21Cycles.join(''));
    }
  });

  var changeActiveTimeout;
  app.getItemDatabase().on('change:active', function(itemModel) {
    // This can be called many times in succession. Wait a bit, canceling
    // previous calls if necessary.
    if (changeActiveTimeout) {
      clearTimeout(changeActiveTimeout);
    }
    changeActiveTimeout = setTimeout(function() {
      checkCycles();
      changeActiveTimeout = null;
    }, 10);
  });

  // Some data may already be available. Activate cycles that were explicitly
  // selected.
  _.each($cyclesValueField.val().split(','), function(cycle) {
    $appWrapper.find('.archibald-lp21-cycles__cycle--cycle-' + cycle + ' input')
      .addClass('archibald-lp21-cycles__cycle__input--hand-selected')
      .prop('checked', true)
      .change();
  });

  // Check'n'lock.
  checkCycles();
});

})(jQuery, window.ArchibaldCurriculum || (window.ArchibaldCurriculum = new Object()));
