<?php

namespace Drupal\component_builder\Plugin\ComponentBuilder;

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

/**
 * Provides 'Table' component.
 *
 * @ComponentBuilder(
 *   id = "table",
 *   label = @Translation("Table"),
 *   group = @Translation("Information"),
 *   category = @Translation("Information"),
 *   template = "table",
 *   single_value = TRUE,
 *   alter_wrapper = TRUE,
 * )
 */
class Table extends ComponentBuilderBase {

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

  /**
   * {@inheritdoc}
   */
  public function prepareVariables(array &$variables) {
    if (isset($variables['elements']['#component_wrapper'])) {
      $component_wrapper = $variables['elements']['#component_wrapper'];
      $component_table = $component_wrapper->get('field_table')->referencedEntities();

      foreach ($component_table as $component_item) {
        if ($component_item instanceof ComponentItem) {
          $cols = [];
          $title = $component_item->getTitle();
          $get_value_cells = $component_item->get('field_cells')->getValue();
          $cols['title'] = $title;
          $cols['cells'] = $get_value_cells;
          $variables['cols'][] = $cols;
        }
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getLibraries() {
    return [
      'css' => [
        'theme' => [
          'components/component_table/assets/style.css' => [],
        ],
      ],
      "version" => "VERSION",
    ];
  }

}
