<?php
namespace SabaiApps\Directories\Component\Faker\Generator;

use SabaiApps\Directories\Component\Field\IField;
use SabaiApps\Directories\Component\Form\Form;
use SabaiApps\Directories\Exception;
use SabaiApps\Directories\Component\Entity\Type\IEntity;

class YouTubeVideoGenerator extends AbstractGenerator {

	protected function _fakerGeneratorInfo() {
		return array(
			'label'            => __( 'YouTube Video Generator', 'directories-pro' ),
			'description'      => __( 'Fetch YouTube videos using YouTube Data API (https://developers.google.com/youtube/v3).', 'directories-pro' ),
			'field_types'      => array( 'video' ),
			'add_probability'  => true,
			'default_settings' => array(
				'max' => 5,
			),
		);
	}

	public function fakerGeneratorSettingsForm( IField $field, array $settings, $mode, array $parents = array() ) {
		$form = array(
			'api_key' => array(
				'#type'                  => 'textfield',
				'#title'                 => __( 'YouTube Data API key', 'directories-pro' ),
				'#description'           => sprintf(
					$this->_application->H( __( 'Get API key from %s.', 'directories-pro' ) ),
					'<a href="https://console.cloud.google.com/" target="_blank" rel="nofollow">Google Cloud Console</a>'
				),
				'#description_no_escape' => true,
				'#required'              => function ( $form ) use ( $parents ) {
					return $form->getValue( array_merge( array_slice( $parents, 0, -2 ), array( 'generator' ) ) ) === 'youtube_videos';
				},
				'#default_value'         => ( $api_key = $this->_application->getPlatform()->getEntityMeta( 'user', $this->_application->getUser()->id, 'faker_youtube_video_api_key' ) ) ? $api_key : null,
				'#element_validate'      => array(
					function ( Form $form, &$value ) {
						if ( empty( $value ) ) {
							return;
						}
						$this->_application->getPlatform()->setEntityMeta( 'user', $this->_application->getUser()->id, 'faker_youtube_video_api_key', $value );
					},
				),
			),
			'q'       => array(
				'#type'          => 'textfield',
				'#title'         => __( 'Keyword', 'directories-pro' ),
				'#description'   => __( 'Enter a keyword for the video search.', 'directories-pro' ),
				'#required'      => true,
				'#default_value' => '',
			),
			'max'     => $this->_getMaxNumItemsSettingForm( $field, $settings['max'], 10 ),
		);
		if ( $mode !== 'new' ) {
			$form['preserve_existing'] = array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Preserve existing', 'directories-pro' ),
				'#description'   => __( 'If checked, existing videos will be preserved and new videos will be added to them.', 'directories-pro' ),
				'#default_value' => true,
			);
		}

		return $form;
	}

	public function fakerGeneratorGenerate( IField $field, array $settings, array &$formStorage, ?IEntity $entity = null ) {
		if ( ! isset( $formStorage['pexels_photos'] ) ) {
			try {
				$params = array(
					'q'          => empty( $settings['q'] ) ? 'nature' : $settings['q'],
					'part'       => 'snippet',
					'type'       => 'video',
					'maxResults' => 50,
					'key'        => $settings['api_key'],
				);
				$url    = 'https://www.googleapis.com/youtube/v3/search';
				$result = $this->_application->getPlatform()->remoteGet( $this->_application->Url( $url, $params, '', '&' ) );
				if ( ! $youtube_videos = json_decode( $result, true ) ) {
					throw new Exception\RuntimeException( 'Failed decoding video list JSON return from YouTube Data API.' );
				}
				$formStorage['youtube_videos'] = (array) $youtube_videos['items'];
			} catch ( \Exception $e ) {
				$this->_application->logError( $e );
				return false;
			}
		}

		$ret       = array();
		$num       = $this->_getMaxNumItems( $field, $settings['max'] );
		$max_index = count( $formStorage['youtube_videos'] ) - 1;
		$i         = 0;
		do {
			++$i;
			$index    = mt_rand( 0, $max_index );
			$video    = $formStorage['youtube_videos'][ $index ];
			$video_id = $video['id']['videoId'];
			if ( isset( $ret[ $video_id ] ) ) {
				continue;
			}

			$ret[ $video_id ] = array(
				'provider'      => 'youtube',
				'id'            => $video_id,
				'title'         => $video['snippet']['title'],
				'thumbnail_url' => $video['snippet']['thumbnails']['high']['url'],
			);
		} while ( count( $ret ) < $num && $i < $num + 10 );

		$ret = array_values( $ret );

		if ( isset( $entity )
			&& ! empty( $settings['preserve_existing'] )
			&& ( $current_videos = $entity->getFieldValue( $field->getFieldName() ) )
		) {
			foreach ( $current_videos as $video ) {
				$ret[] = $video;
			}
		}

		return $ret;
	}
}
