<?php

class MbVideoThumbnailRetriever {
  /**
   * Registered components
   *
   * @var array<int,\MBComponentBase|\MBRetrievesVideoThumbnails>
   */
  private array $components;

  public function __construct(array $components = []) {
    $this->components = $components;
  }

  /**
   * Register component
   *
   * @param MBRetrievesVideoThumbnails $component
   * @return void
   */
  public function register(MBRetrievesVideoThumbnails $component) {
    $this->components[] = $component;
  }

  /**
   * Run thumb retriever
   *
   * @return void
   */
  public function run() {
    foreach ($this->components as $component) {
      add_action("wp_ajax_mb_blocks_save", function () use ($component) {
        $request = rwmb_request();
        $id = $component->get_mb()["id"];
        $fields = $component->videoThumbnailFields();

        if (!$id || $request->post("block") !== "meta-box/$id") {
          return;
        }

        foreach ($fields as $video_field => $thumb_field) {
          $video = $request->post($video_field);

          $request->set_post_data([
            $thumb_field => $this->getThumbUrlForVideo($video) ?? self::placeholder(),
          ]);
        }
      });
    }
  }

  /**
   * Get default video thumbnail placeholder
   *
   * @return string Url of the placeholder
   */
  public static function placeholder() {
    return get_theme_file_uri("assets/images/video-placeholder.png");
  }

  /**
   * Retrieve video thumbanil from youtube/vimeo
   *
   * @param string|null $video Video url
   * @return string|null
   */
  private function getThumbUrlForVideo($video) {
    // No video provided - exit
    if (!$video) {
      return null;
    }
    // Handle youtube video
    if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/\s]{11})%i', $video, $match)) {
      $video_id = $match[1];
      if (!$video_id) {
        return null;
      }
      // build thumb url
      return "https://img.youtube.com/vi/$video_id/maxresdefault.jpg";
    }
    // Handle vimeo video
    if (preg_match('%^https?:\/\/(?:www\.|player\.)?vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/([^\/]*)\/videos\/|album\/(\d+)\/video\/|video\/|)(\d+)(?:$|\/|\?)(?:[?]?.*)$%im', $video, $match)) {
      $video_id = $match[3];
      if (!$video_id) {
        return null;
      }
      // get info about video
      $res = wp_remote_get("https://vimeo.com/api/v2/video/$video_id.json");
      if ($res instanceof WP_Error) {
        return null;
      }
      // get thumb url from response
      $url = json_decode($res["body"])[0]->thumbnail_large ?? null;
      // change protocol to secure
      return $url ? str_replace("http://", "https://", $url) : null;
    }

    return null;
  }
}
