<?php

namespace Drupal\component_builder;

/**
 * Provides a method for component wrapper form.
 */
trait ComponentWrapperFormTrait {

  /**
   * Get weight of group.
   */
  protected function getDefaultWeightGroup(string $group = '') {
    $config_weights = \Drupal::config('component_builder.settings')->get('weight_component');
    if (isset($config_weights[$group])) {
      return $config_weights[$group];
    }
    return 10000;
  }

  /**
   * @deprecated in 3.3.0 and is removed from 4.0.x when term change to config entity.
   */
  public function getComponentNameWithTerm($options, $id) {
    if (isset($options[$id])) {
      $str = strtolower($options[$id]);
      return str_replace(' ', '_', $str);
    }
  }

  /**
   * Get array properties of component.
   */
  public function renderProperties(&$entity_form, $properties, $values) {
    if ($values) {
      $values = json_decode($values, TRUE);
    }

    foreach ($properties as $key => $property) {
      $types = $property;
      $label = $property['label'];
      $entity_form[$key] = [
        '#type' => 'details',
        '#title' => $label,
        '#open' => TRUE,
      ];
      unset($types['label']);

      foreach ($types as $type_name => $items) {
        $entity_form[$key][$type_name] = [
          '#type' => 'fieldset',
          '#title' => ucfirst($type_name),
          '#tree' => TRUE,
        ];

        foreach ($items as $item_name => $options) {
          $options = ['_none' => '-- xNone --'] + $options;
          $entity_form[$key][$type_name][$item_name] = [
            '#type' => 'select',
            '#title' => t('Select') . ' ' . str_replace('_', ' ', $item_name),
            '#options' => $options,
          ];
          if (isset($values[$key][$type_name][$item_name])) {
            $entity_form[$key][$type_name][$item_name]['#default_value'] = $values[$key][$type_name][$item_name];
          }
        }
      }
    }
  }

  public function getDefaultComponent($options, $name) {
    foreach ($options as $id => $option) {
      if ($option == $name) {
        return $id;
      }
    }
    return array_key_first($options);
  }

  public function filterComponents($options) {
    return $options;
  }

}
