/**
 * @file
 * Dynamic format options for Converted Video formatter settings.
 *
 * Updates the "Enabled formats" checkboxes when the conversion profile
 * selection changes on the Manage Display page. Uses drupalSettings to
 * avoid AJAX round-trips (Drupal's Entity Display subform context does
 * not support #ajax on formatter settings elements).
 */

(function ($, Drupal, drupalSettings, once) {
  'use strict';

  Drupal.behaviors.ffmpegFormatterSettings = {
    attach: function (context) {
      once('ffmpeg-formatter-settings-listener', 'html', context).forEach(
        function () {
          // Delegate from document so dynamic formatter subforms are covered.
          $(document).on(
            'change.ffmpegFormatterSettings',
            'select[data-ffmpeg-profile-select]',
            function () {
              var config = drupalSettings.ffmpegFormatter || {};
              var profiles = config.profiles || {};
              var defaultProfile = config.defaultProfile || '';

              updateFormats(this, profiles, defaultProfile);
            }
          );
        }
      );

      once(
        'ffmpeg-formatter-settings-init',
        'select[data-ffmpeg-profile-select]',
        context
      ).forEach(function (select) {
        var config = drupalSettings.ffmpegFormatter || {};
        var profiles = config.profiles || {};
        var defaultProfile = config.defaultProfile || '';
        updateFormats(select, profiles, defaultProfile);
      });
    }
  };

  /**
   * Updates the format checkboxes for the given profile select.
   *
   * @param {HTMLSelectElement} select
   *   The conversion profile select element.
   * @param {Object} profiles
   *   All profile format data from drupalSettings.
   * @param {string} defaultProfile
   *   The default profile ID.
   */
  function updateFormats(select, profiles, defaultProfile) {
    var profileId = select.value || defaultProfile;
    var formats = profiles[profileId];

    if (!formats) {
      return;
    }

    var $container = $(select).closest(
      '.field-plugin-settings-edit-form'
    );

    if (!$container.length) {
      return;
    }

    var $wrapper = $container.find('[data-ffmpeg-format-priority]');

    if (!$wrapper.length) {
      return;
    }

    // Collect currently checked formats to preserve selections.
    var checked = {};
    $wrapper.find('input[type="checkbox"]').each(function () {
      if (this.checked) {
        checked[this.value] = true;
      }
    });

    // Update each checkbox: show if in profile, hide if not.
    $wrapper.find('.js-form-item, .form-item').each(function () {
      var $item = $(this);
      var cb = $item.find('input[type="checkbox"]')[0];

      if (!cb) {
        return;
      }

      var key = cb.value;

      if (formats[key]) {
        $item.show();
        cb.disabled = false;
        $item.find('label').text(formats[key]);

        // Check newly visible formats by default.
        if (!checked[key] && $item.data('ffmpegHidden')) {
          cb.checked = true;
        }

        $item.removeData('ffmpegHidden');
      }
      else {
        $item.hide();
        cb.disabled = true;
        $item.data('ffmpegHidden', true);
        cb.checked = false;
      }
    });
  }

})(jQuery, Drupal, drupalSettings, once);
