<?php

namespace Drupal\component_builder\Plugin\ComponentBuilder;

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

/**
 * Provides 'Grid' component.
 *
 * @ComponentBuilder(
 *   id = "grid",
 *   label = @Translation("Grid"),
 *   group = @Translation("Grid Style"),
 *   category = @Translation("Grid Style"),
 *   template = "grid"
 * )
 */
class Grid extends ComponentBuilderBase {

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

  /**
   * {@inheritdoc}
   */
  public function prepareVariables(array &$variables): void {
    if (isset($variables['elements']['#component_wrapper'])) {
      $component_wrapper = $variables['elements']['#component_wrapper'];
      if ($component_wrapper instanceof ComponentWrapper) {
        $number = 1;

        $properties = $component_wrapper->get('field_properties')->value;
        if ($properties) {
          $properties = json_decode($properties, TRUE);
          foreach ($properties as $property) {
            foreach ($property as $key => $elements) {
              if ($key === "styles" && isset($elements["number-columns"])) {
                $number = (int) $elements["number-columns"];
              }
            }
          }
        }

        $items = $component_wrapper->get('field_grid')->getValue();
        $number_items = count($items);
        if ($number_items && count($items) > $number) {
          for ($i = $number; $i < $number_items; $i++) {
            if (isset($variables['elements']['field_grid'][$i])) {
              // unset($variables['content']['field_grid'][$i]);.
            }
          }
        }
      }
    }

    if (isset($variables['elements']['#component_item'])) {
      $component_item = $variables['elements']['#component_item'];
      if ($component_item instanceof ComponentItem) {
        $field_link = $component_item->get('field_link')->getValue();
        if ($field_link) {
          if (!$field_link[0]['title']) {
            if ($variables['content']['title']['0']) {
              $variables['content']['field_link']['0']['#title'] = $variables['content']['title'][0]['#context']['value'];
            }
          }
        }
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getLibraries(): array {
    return [
      'css' => [
        'theme' => [
          'components/component_grid/assets/style.css' => [],
        ],
      ],
      'js' => [
        'components/component_grid/assets/style.js' => [],
        'https://cdnjs.cloudflare.com/ajax/libs/jquery.matchHeight/0.7.2/jquery.matchHeight-min.js' => [
          'type' => 'external',
          'minified' => TRUE,
        ],
      ],
      'dependencies' => [
        'core/jquery',
        'core/drupal',
        'core/jquery.once',
      ],
      "version" => "VERSION",
    ];
  }

}
