/**
 * @file
 * Behaviors for the settings component form.
 */

(function ($, Drupal, once) {

  'use strict';

  Drupal.componentSettings = Drupal.componentSettings || {};
  Drupal.behaviors.componentSettings = {
    attach: function (context) {
      Drupal.componentSettings.setEvent(context);
      Drupal.componentSettings.checkUnCheckAll(context);
      Drupal.componentSettings.collapseAll(context);
    }
  }

  Drupal.componentSettings.setEvent = function (context) {
    const $wrapper_checkboxes = $(once('wrapperCheckboxes', '.wrapper-checkbox', context));
    if ($wrapper_checkboxes.length > 0) {
      $wrapper_checkboxes.each(function () {
        const $this = $(this);
        const $image_collapse = $this.find('.collapse-image');
        if ($image_collapse.length > 0) {
          $this.addClass('has-image');
        }
      })
    }

    const $next = $('.checkbox-component').next();
    const $label = $(once('labelCheckbox', $next));
    if ($label.length > 0) {
      $label.click(function (e) {
        e.preventDefault();
        e.stopPropagation();
        const $parent = $(this).closest('.wrapper-checkbox');
        $parent.toggleClass('active');
        const $image = $parent.find('.collapse-image');
        if ($image.length > 0) {
          $parent.addClass('has-image');
        }
        if ($image.length > 0) {
          $image.toggleClass('visually-hidden');
        }
      })
    }
  }

  Drupal.componentSettings.checkUnCheckAll = function (context) {
    const $wrapper_check_uncheck_all = $(once('wrapperCheckUnCheckAll', ".wrapper-checkbox-check-uncheck-all", context));
    if ($wrapper_check_uncheck_all.length > 0) {
      $wrapper_check_uncheck_all.on("click", function () {
        $('.wrapper-checkbox .checkbox-component').prop('checked', $(this).prop('checked'));
      });
    }
  };

  Drupal.componentSettings.collapseAll = function (context) {
    const $wrapper_collapse_all = $(once('wrapperCollapseAll', ".wrapper-collapse-all", context));
    if ($wrapper_collapse_all.length > 0) {
      $wrapper_collapse_all.on("click", function (e) {
        e.preventDefault();
        e.stopPropagation();
        const $details = $('.wrapper-collapse-group-component');
        const attr = $details.attr('open');
        if (typeof attr === 'undefined') {
          $details.attr('open', '');
        }
        else {
          $details.removeAttr('open');
        }
      });
    }
  };

})(jQuery, Drupal, once);
