<?php

namespace Drupal\component_builder\Plugin\ComponentBuilder;

use Drupal\component_builder\ComponentBuilderBase;
use Drupal\Core\Render\Element;

/**
 * Provides 'Timeline' component.
 *
 * @ComponentBuilder(
 *   id = "timeline",
 *   label = @Translation("Timeline"),
 *   group = @Translation("Listing"),
 *   category = @Translation("Listing"),
 *   template = "timeline",
 *   alter_wrapper = TRUE,
 *   dependencies = {
 *      "video_embed_field": {
 *         "label" : "Video Embed Field",
 *         "url" : "https://www.drupal.org/project/video_embed_field"
 *       }
 *    }
 * )
 */
class Timeline 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->hasField('field_timelines_wrapper')) {
        $field_timeline_wrapper = $component_wrapper->get('field_timelines_wrapper')
          ->getValue();
        if (!empty($field_timeline_wrapper)) {
          $variables['is_parent'] = TRUE;
          if ($variables['content']['field_timelines_wrapper']) {
            $children_content = Element::children($variables['content']['field_timelines_wrapper']);
            foreach ($children_content as $key) {
              $variables['items'][] = $variables['content']['field_timelines_wrapper'][$key];
            }
          }
        }
      }
    }
  }

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

}
