<?php

namespace Drupal\component_builder\Plugin\ComponentBuilder;

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

/**
 * Provides 'Composite' component.
 *
 * @ComponentBuilder(
 *   id = "composite",
 *   label = @Translation("Composite"),
 *   group = @Translation("Site Function"),
 *   category = @Translation("Site Function"),
 *   template = "composite"
 * )
 */
class Composite 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) {
        $class_options = '';
        $layout = [];
        $column = '';
        $properties = $component_wrapper->get('field_properties')->value;
        if ($properties) {
          $properties = json_decode($properties, TRUE);
          if (isset($properties['properties']['options']['column']) && $properties['properties']['options']['column'] !== '_none') {
            $column = $properties['properties']['options']['column'];
          }
          if (isset($properties['properties']['styles']['layout']) && $properties['properties']['styles']['layout'] !== '_none') {
            $layout = $properties['properties']['styles']['layout'];
            $class_options = str_replace('column-', '', $layout);
            $layout = str_replace('column-', '', $layout);
            $layout = explode('-', $layout);
          }
          $column = $column ?? 2;
          switch ($column) {
            case 1:
              $class_options = $class_options ?: '12';
              $variables['left_column_with'] = 12;
              break;

            case 2:
              $class_options = $class_options ?: '6-6';
              $variables['left_column_with'] = $layout[0] ?? 6;
              $variables['right_column_with'] = $layout[1] ?? 6;
              break;

            case 3:
              $class_options = $class_options ?: '4-4-4';
              $variables['left_column_with'] = $layout[0] ?? 4;
              $variables['middle_column_with'] = $layout[1] ?? 4;
              $variables['right_column_with'] = $layout[2] ?? 4;
              break;
          }
          $variables['attributes']['data-number-columns'][] = $column;
          $variables['attributes']['data-column-class'][] = $class_options;
        }
      }
    }
  }

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

}
