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

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

class PicsumPhotoGenerator extends AbstractGenerator {

	protected function _fakerGeneratorInfo() {
		return array(
			'label'            => __( 'Picsum Photo Generator', 'directories-pro' ),
			'description'      => __( 'Download random photos from https://picsum.photos/.', 'directories-pro' ),
			'field_types'      => array( 'wp_image' ),
			'add_probability'  => true,
			'default_settings' => array(
				'max' => 5,
			),
		);
	}

	public function fakerGeneratorSettingsForm( IField $field, array $settings, $mode, array $parents = array() ) {
		$form = array(
			'max' => $this->_getMaxNumItemsSettingForm( $field, $settings['max'] ),
		);
		if ( $mode !== 'new' ) {
			$form['preserve_existing'] = array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Preserve existing', 'directories-pro' ),
				'#description'   => __( 'If checked, existing photos will be preserved and new photos will be added to them.', 'directories-pro' ),
				'#default_value' => true,
			);
		}
		return $form;
	}

	public function fakerGeneratorGenerate( IField $field, array $settings, array &$formStorage, ?IEntity $entity = null ) {
		try {
			$result = $this->_application->getPlatform()->remoteGet( 'https://picsum.photos/v2/list?page=' . mt_rand( 1, 33 ) );
			if ( ! $picsum_photos = json_decode( $result, true ) ) {
				throw new Exception\RuntimeException( 'Failed decoding photo list JSON return from picsum.photos.' );
			}
		} catch ( \Exception $e ) {
			$this->_application->logError( $e );
			return false;
		}

		if ( ! isset( $formStorage['picsum_photos'] ) ) {
			$formStorage['picsum_photos'] = array();
		}

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

			if ( ! isset( $formStorage['picsum_photos'][ $photo['id'] ] ) ) {
				$url = 'https://picsum.photos/1280/720?image=' . $photo['id'];
				try {
					$file_path = $this->_application->getPlatform()->downloadUrl( $url );
				} catch ( \Exception $e ) {
					$this->_application->logError( $e );
					continue;
				}

				try {
					$file = $this->_application->getPlatform()->uploadFile(
						$file_path,
						'picsum-photo-' . $photo['id'] . '.jpeg',
						sprintf( 'Photo by %s', $photo['author'] )
					);
				} catch ( \Exception $e ) {
					@unlink( $file_path );
					$this->_application->logError( $e );
					continue;
				}

				$formStorage['picsum_photos'][ $photo['id'] ] = $file;
			}

			$ret[ $photo['id'] ] = $formStorage['picsum_photos'][ $photo['id'] ];

		} while ( count( $ret ) < $num && $i < $num + 5 );

		$ret = array_values( $ret );

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

		return $ret;
	}
}
