<?php

class WPML_Page_Builders_Media_Translate implements IWPML_PB_Media_Find_And_Translate {

	private $element_factory;

	protected $image_translate;

	protected $translated_urls = array();

	protected $translated_posts = array();

	private $translated_ids = array();

	public function __construct(
		WPML_Translation_Element_Factory $element_factory,
		WPML_Media_Image_Translate $image_translate
	) {
		$this->element_factory = $element_factory;
		$this->image_translate = $image_translate;
	}

	public function prefetch_media_urls( array $urls, $source_lang ) {
		if ( empty( $urls ) ) {
			return;
		}
		$items_to_translate = array_map(
			function ( $url ) {
				return array( 'url' => $url );
			},
			$urls
		);
		$this->image_translate->prefetchDataForFutureGetTranslatedImageCalls( $source_lang, $items_to_translate );
	}

	public function translate_image_url( $url, $lang, $source_lang, $tag_name = '' ) {
		$key = $url . $lang . $source_lang;

		if ( ! array_key_exists( $key, $this->translated_urls ) ) {
			$this->translated_urls[ $key ] = $url;

			$attachment_id = $this->image_translate->get_attachment_id_by_url( $url, $source_lang );

			if ( $attachment_id ) {
				$this->add_translated_id( $attachment_id );
				$translated_url                = $this->image_translate->get_translated_image_by_url( $url, $source_lang, $lang );
				$this->translated_urls[ $key ] = $url;

				if ( $translated_url ) {
					$this->translated_urls[ $key ] = $translated_url;
				}
			}
		}

		return $this->translated_urls[ $key ];
	}

	public function translate_id( $id, $lang ) {
		if ( (int) $id < 1 ) {
			return $id;
		}

		$this->add_translated_id( $id );
		$translated_attachment = $this->get_translated_attachment( $id, $lang );

		if ( isset( $translated_attachment->ID ) ) {
			return $translated_attachment->ID;
		}

		return $id;
	}

	private function get_translated_attachment( $id, $lang ) {
		$key = $id . $lang;

		if ( ! array_key_exists( $key, $this->translated_posts ) ) {
			$this->translated_posts[ $key ] = null;
			$element                        = $this->element_factory->create_post( $id );
			$translation                    = $element->get_translation( $lang, true );

			if ( $translation ) {
				$this->translated_posts[ $key ] = $translation->get_wp_object();
			}
		}

		return $this->translated_posts[ $key ];
	}

	private function add_translated_id( $id ) {
		if ( ! in_array( $id, $this->translated_ids, true ) ) {
			$this->translated_ids[] = $id;
		}
	}

	public function reset_translated_ids() {
		$this->translated_ids = array();
	}

	public function get_translated_ids() {
		return $this->translated_ids;
	}

	public function get_used_media_in_post() {
		return [];
	}
}
