<?php

namespace WP_AUX\Entities;

use WP_AUX\Entities\ComponentEntity;

class ComponentAugmentorEntity {
  protected ?ComponentEntity $component;

  protected array $augmentations = [];
  protected array $augmentationsSelected = [];

  public function __construct(ComponentEntity $component, array $augmentations = []) {
    $this->component = $component;

    if (!empty($augmentations)) {
      $this->prepareAugmentations($augmentations);
    }
  }

  protected function prepareAugmentations(array $rawAugmentations): void
  {
    foreach ($rawAugmentations as $augmentationKey => $augmentationValue) {
      if (is_int($augmentationKey)) {
        $this->augmentations[$augmentationValue]['classes'] = [ "--{$augmentationValue}" ];
      } else {
        $this->augmentations[$augmentationKey]['classes'] = !empty($augmentationValue) ? (array) $augmentationValue : [];
      }
    }
  }

  public function setAugmentation(string $augmentation): self
  {
    $this->augmentationsSelected = [ $augmentation ];

    return $this;
  }

  public function getChildAugmentations(): array
  {
    $childAugmentations = [];

    foreach ($this->augmentationsSelected as $augmentationSelected) {
      if (!empty( $this->augmentations[$augmentationSelected]['childAugmentations'] )) {
        $childAugmentations = array_merge($childAugmentations, $this->augmentations[$augmentationSelected]['childAugmentations']);
      }
    }

    return $childAugmentations;
  }

  public function getClassesString(): string
  {
    $classes = [];

    $classPrefix = $this->component::ELEMENT_PRIMARY_CLASS;

    foreach ($this->augmentationsSelected as $augmentationName) {
      $augmentationClasses = $this->augmentations[$augmentationName]['classes'];

      if (empty($augmentationClasses)) {
        continue;
      }

      foreach ($augmentationClasses as $class) {
        if (strpos($class, '--') === 0) {
          $classes[] = $classPrefix . $class;
        } else {
          $classes[] = $class;
        }
      }
    }

    return join(' ', $classes);
  }
}
