<?php

namespace WP_AUX\Entities;

use WP_AUX\Entities\Components\SectionWrapEntity;
use WP_AUX\Entities\Components\Traits\ComponentAugmentorTraits;

class ComponentEntity {
  use ComponentAugmentorTraits;

  public const ELEMENT_PRIMARY_CLASS = '';

  protected ?ComponentEntity $wrapper = null;

  protected string $contents = '';

  protected string $style = 'default';

  protected array $additionalClasses = [];

  public function __construct(string $contents = '')
  {
    $this->contents = $contents;

    $this->prepareAugmentors();

    $this->init();
  }

  public function init(): static
  {
    return $this;
  }

  public function doSectionWrap(): static
  {
    $this->wrapper = SectionWrapEntity::create();

    return $this;
  }

  public function setStyle(string $style = ''): static
  {
    $this->style = $style;

    $this->setAugmentation('style', $style);

    return $this;
  }

  public function setContents(string $contents): static
  {
    $this->contents = $contents;

    return $this;
  }

  public function getContents(): string
  {
    return (string) $this->contents;
  }

  public function startContentsFromBuffer(): static
  {
    $this->contents = '';

    ob_start();

    return $this;
  }

  public function setContentsFromBuffer(): static
  {
    $this->contents = ob_get_clean();

    return $this;
  }

  public function addClasses(string|array $classes): static
  {
    $this->additionalClasses = array_unique(array_merge($this->additionalClasses, $classes));

    return $this;
  }

  public function getClasses(): array
  {
    return array_unique(array_merge(
      [ static::ELEMENT_PRIMARY_CLASS ],
      $this->getAugmentorsClasses(),
      $this->additionalClasses
    ));
  }

  public function renderPattern(): string
  {
    return '<div class="%s">%s</div>';
  }

  public function renderArguments(): array
  {
    return [
      'classes' => join(' ', $this->getClasses()),
      'contents' => $this->getContents(),
    ];
  }

  public function __toString(): string
  {
    $html = vsprintf($this->renderPattern(), $this->renderArguments());

    if (!empty($this->wrapper)) {
      $wrapper = $this->wrapper;
      $wrapper->setContents($html);

      return (string) $wrapper;
    }

    return $html;
  }

  public static function create(string $contents = ''): static
  {
    return new static($contents);
  }
}
