<?php

namespace Drupal\component_builder\Plugin\ComponentBuilder;

use Drupal\component_builder\ComponentBuilderBase;
use Drupal\component_builder\Entity\ComponentItem;

/**
 * Provides 'Flexible Grid' component.
 *
 * @ComponentBuilder(
 *   id = "flexible_grid",
 *   label = @Translation("Flexible Grid"),
 *   group = @Translation("Grid Style"),
 *   category = @Translation("Grid Style"),
 *   template = "flexible_grid",
 *   dependencies = {
 *     "color_field": {
 *       "label" : "Color field",
 *       "url" : "https://www.drupal.org/project/color_field"
 *     }
 *   }
 * )
 */
class FlexibleGrid extends ComponentBuilderBase {

  /**
   * {@inheritdoc}
   */
  public function prepareVariables(array &$variables) {
    if (isset($variables['elements']['#component_item'])) {
      $component_item = $variables['elements']['#component_item'];
      if ($component_item instanceof ComponentItem) {
        unset(
          $variables['content']['field_fg_item_type'],
          $variables['content']['field_fg_background_color']
        );
        $field_item_type = $component_item->get('field_fg_item_type')
          ->getString();
        $variables['content']['grid_type'] = $field_item_type;
        $field_background_color = $component_item->get('field_fg_background_color');
        if ($field_background_color) {
          $variables['content']['background_color'] = $field_background_color->getString();
        }
        if (isset($variables['content'])) {
          if ($field_item_type === 'grid_image_text') {
            unset(
              $variables['content']['field_fg_icon_image'],
            );
          }
          elseif ($field_item_type === 'grid_icon') {
            unset(
              $variables['content']['field_fg_short_description'],
              $variables['content']['field_fg_big_image'],
            );
          }
        }
        $variables['attributes']['grid_type'] = $field_item_type;
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getTemplatePath() {
    return $this->getComponentPath() . '/templates';
  }

  /**
   * {@inheritdoc}
   */
  public function getLibraries() {
    return [
      'css' => [
        'theme' => [
          'components/component_flexible_grid/assets/style.css' => [],
        ],
      ],
      'js' => [
        'components/component_flexible_grid/assets/style.js' => [],
      ],
      'dependencies' => [
        'core/drupal',
        'core/jquery',
        'core/jquery.once',
      ],
      "version" => "VERSION",
    ];
  }

}
