<?php

namespace Drupal\component_builder\Plugin\ComponentBuilder;

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

/**
 * Provides 'Related Content' component.
 *
 * @ComponentBuilder(
 *   id = "related_content",
 *   label = @Translation("Related Content"),
 *   group = @Translation("Grid Style"),
 *   category = @Translation("Grid Style"),
 *   template = "related_content",
 * )
 */
class RelatedContent 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) {
        $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") {
                if (isset($elements["columns"])) {
                  $number = (int) $elements["columns"];
                }
              }
            }
          }
        }
        $variables['attributes']['data-related-content-columns'][] = $number;
      }
    }
  }

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

}
