<?php

namespace Drupal\component_builder\Plugin\ComponentBuilder;

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

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

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

  /**
   * {@inheritdoc}
   */
  public function prepareVariables(array &$variables) {
    if (isset($variables['elements']['#component_wrapper'])) {
      $hidden_fields = [];
      $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["carousel-columns"])) {
                  $number = (int) $elements["carousel-columns"];
                }
              }
              if ($key === "options") {
                if (isset($elements["carousel-types"])) {
                  if ($elements["carousel-types"] === "image") {
                    $hidden_fields[] = 'field_image';
                    $variables['attributes']['data-hidden-field'] = json_encode($hidden_fields);
                  }
                }
              }
            }
          }
        }
        $variables['attributes']['data-carousel-columns'][] = $number;
      }
    }
    if (isset($variables['elements']['#component_item'])) {
      $language = \Drupal::languageManager()->getCurrentLanguage();
      $variables['#attached']['drupalSettings']['components']['grid_carousel']['rtl'] = $language->getDirection() === 'rtl';
    }
  }

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

}
