<?php

namespace WP_AUX\Entities\Components\Traits;

use WP_AUX\Entities\Augmentors\DarkmodeAugmentorEntity;
use WP_AUX\Entities\ComponentAugmentorEntity;
use WP_AUX\Entities\ComponentEntity;

trait ComponentAugmentorTraits {
  protected static array $augmentations = [];

  protected static array $defaultAugmentors = [
    'darkmode' => DarkmodeAugmentorEntity::class,
  ];

  /**
   * @var ComponentAugmentorEntity[]
   */
  protected array $augmentors = [];

  protected function prepareAugmentors(): void
  {
    if (!empty($this->augmentors)) {
      foreach ($this->augmentors as $augmentorName => $augmentorClass) {
        $this->augmentors[$augmentorName] = new $augmentorClass($this);
      }
    }

    if (!empty(static::$defaultAugmentors)) {
      foreach (static::$defaultAugmentors as $augmentorName => $augmentorClass) {
        $this->augmentors[$augmentorName] = new $augmentorClass($this);
      }
    }

    if (!empty(static::$augmentations)) {
      $this->registerAugmentors(static::$augmentations);
    }
  }

  protected function registerAugmentors($augmentations): static
  {
    foreach ($augmentations as $augmentationKey => $augmentation) {
      $this->registerAugmentor($augmentationKey, $augmentation);
    }

    return $this;
  }

  protected function registerAugmentor(string $augmentorName, array $augmentations): static
  {
    $this->augmentors[$augmentorName] = new ComponentAugmentorEntity($this, $augmentations);

    return $this;
  }

  public function setAugmentation(string $augmentorName, string $augmentation): static
  {
    $augmentor = @$this->augmentors[$augmentorName];

    if ($augmentor) {
      $augmentor->setAugmentation($augmentation);
    }

    return $this;
  }

  public function setChildAugmentations(string $augmentorName, ComponentEntity $childComponent): static
  {
    $augmentor = @$this->augmentors[$augmentorName];

    if ($augmentor) {
      if ($childAugmentations = $augmentor->getChildAugmentations()) {
        foreach ($childAugmentations as $augmentationHash) {
          list($augmentationKey, $augmentationValue) = explode('.', $augmentationHash);
          $childComponent->setAugmentation($augmentationKey, $augmentationValue);
        }
      }
    }

    return $this;
  }

  protected function getAugmentorsClasses(): array
  {
    $classes = [];

    if (!empty($this->augmentors)) {
      foreach ($this->augmentors as $augmentorName => $augmentor) {
        $classes[] = $augmentor->getClassesString();
      }
    }

    return $classes;
  }
}
