<?php

namespace Drupal\component_builder\Plugin\ComponentBuilder;

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

/**
 * Provides 'Carousel' component.
 *
 * @ComponentBuilder(
 *   id = "carousel",
 *   label = @Translation("Carousel"),
 *   group = @Translation("Slider"),
 *   category = @Translation("Slider"),
 *   template = "carousel"
 * )
 */
class Carousel 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;
        $dot = 'false';
        $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 ($elements["show_dot"] == '1') {
                  $dot = 'true';
                }
                else {
                  $dot = 'false';
                }
              }
            }
          }
        }
        $variables['attributes']['data-show-dot'][] = $dot;
        $variables['attributes']['data-carousel-columns'][] = $number;
      }
    }
    if (isset($variables['elements']['#component_item'])) {
      $language = \Drupal::languageManager()->getCurrentLanguage();
      $variables['#attached']['drupalSettings']['components']['carousel']['rtl'] = $language->getDirection() === 'rtl';
    }
  }

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

}
