<?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 'Card' component.
 *
 * @ComponentBuilder(
 *   id = "card",
 *   label = @Translation("Card"),
 *   group = @Translation("Grid Style"),
 *   category = @Translation("Grid Style"),
 *   single_value = TRUE,
 *   template = "card"
 * )
 */
class Card 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-card-columns'][] = $number;
      }
    }
    if (isset($variables['elements']['#component_item'])) {
      $component_item = $variables['elements']['#component_item'];
      if ($component_item instanceof ComponentItem) {
        $fieldCardColor = $component_item->get('field_card_color')->getString();
        if ($fieldCardColor) {
          $variables['attributes']['class'][] = 'item-background-color-' . $fieldCardColor;
        }
      }
    }
  }

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

}
