<?php
declare(strict_types=1);

namespace WP_AUX\Entities\Embeds\VideoSource;

use WHOOP\Entities\Element;
use WHOOP\Entities\Elements\Video;
use WP_AUX\Entities\Embeds\VideoSourceEntity;

class HtmlVideoSourceEntity extends VideoSourceEntity
{
  public static bool $isIframe = false;

  public function linkUrl(): string
  {
    return get_the_permalink();
  }

  /**
   * @param Video $element
   */
  protected function prepareElement($element): void
  {
    if ($this->autoplay) {
      $element->setAttribute('autoplay', null);
      $element->setAttribute('muted', null);
    } else {
      if ($this->muted) {
        $element->setAttribute('muted', null);
      }
    }

    if (false === $this->disableControls) {
      $element->setAttribute('controls', null);
    }

    if ($this->loop) {
      $element->setAttribute('loop', null);
    }

    $element->setAttribute('title', $this->title);
  }

  /**
   * @return Video|null
   */
  public function getElement(): ?Element
  {
    if (empty($this->url)) {
      return null;
    }

    $source = sprintf(
      '<source src="%s" type="%s" />',
      $this->url,
      $this->mimeType
    );

    $element = Video::create($source);

    $this->prepareElement($element);

    return $element;
  }

  public static function create(
    string|array $video,
    ?string $title = null
  ): static
  {
    if (is_array($video)) {
      $url = $video['url'];
      $title = $video['title'];
    } else {
      $url = $video;
    }

    $videoSource = new static($url, $title);

    if (
      $url &&
      $checkType = wp_check_filetype(parse_url($url, PHP_URL_PATH), wp_get_mime_types())
    ) {
      if (isset($checkType['type'])) {
        $videoSource->setMimeType(is_bool($checkType['type']) ? null : $checkType['type']);
      }
    }

    return $videoSource;
  }
}
