<?php

namespace Drupal\component_builder\Plugin\ComponentBuilder;

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

/**
 * Provides 'Tree Structure' component.
 *
 * @ComponentBuilder(
 *   id = "tree_structure",
 *   label = @Translation("Tree Structure"),
 *   group = @Translation("Model"),
 *   category = @Translation("Model"),
 *   template = "tree_structure",
 *   alter_wrapper = TRUE
 * )
 */
class TreeStructure 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'];
      if ($component_wrapper instanceof ComponentWrapper) {
        $title_wrapper = $component_wrapper->getTitle();
        $variables['#attached']['drupalSettings']['components']['tree_structure']['root'] = $title_wrapper;
      }
      $field_tree_structure = $component_wrapper->get('field_tree_structure')->referencedEntities();
      foreach ($field_tree_structure as $component_item) {
        if ($component_item instanceof ComponentItem) {
          $single_item = [];
          $title_item = $component_item->getTitle();
          $field_leaves = $component_item->get('field_leaves')->getValue();
          $single_item['parent'] = $title_item;
          $single_item['leaves'] = $field_leaves;
          $variables['#attached']['drupalSettings']['components']['tree_structure']['items'][] = $single_item;
        }
      }
    }
  }

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

}
