<?php

namespace Drupal\component_builder\Plugin\ComponentBuilder;

use Drupal\component_builder\ComponentBuilderBase;

/**
 * Provides 'Chart' component.
 *
 * @ComponentBuilder(
 *   id = "chart",
 *   label = @Translation("Chart"),
 *   group = @Translation("Information"),
 *   category = @Translation("Information"),
 *   template = "chart",
 *   single_value = TRUE,
 *   alter_wrapper = TRUE
 * )
 */
class Chart 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'];
      $field_chart = $component_wrapper->get('field_chart')
        ->referencedEntities();
      $items = [['X value', 'Y value']];
      if ($field_chart) {
        foreach ($field_chart as $item) {
          if ($item->hasField('field_x_value') && $item->hasField('field_y_value')) {
            $x_value = $item->get('field_x_value')->value ? (int) $item->get('field_x_value')->value : 0;
            $y_value = $item->get('field_y_value')->value ? (int) $item->get('field_y_value')->value : 0;
            $items[] = [
              $x_value,
              $y_value,
            ];
          }
        }
      }
      $variables['#attached']['drupalSettings']['components']['chart']['items'] = json_encode(array_values($items));
      $variables['#attached']['drupalSettings']['components']['chart']['title'] = $component_wrapper->label();

      $properties = $component_wrapper->get('field_properties')->value;
      if ($properties) {
        $properties = json_decode($properties, TRUE);
        if (isset($properties['properties']['styles']['chart-type']) && $properties['properties']['styles']['chart-type'] !== '_none') {
          $variables['#attached']['drupalSettings']['components']['chart']['type'] = $properties['properties']['styles']['chart-type'];

        }
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getLibraries() {
    return [
      'css' => [
        'theme' => [
          'components/component_chart/assets/style.css' => [],
        ],
      ],
      'js' => [
        'https://www.gstatic.com/charts/loader.js' => [
          'type' => 'external',
        ],
        'components/component_chart/assets/style.js' => [],
      ],
      'dependencies' => [
        'core/drupal',
        'core/jquery',
        'core/jquery.once',
      ],
      "version" => "VERSION",
    ];
  }

}
