<?php
namespace SabaiApps\Directories\Component\DirectoryPro\FieldRenderer;

use SabaiApps\Directories\Component\Field;
use SabaiApps\Directories\Component\Entity;

class ScreenshotFieldRenderer extends Field\Renderer\ImageRenderer {

	protected function _fieldRendererInfo() {
		$info                                 = array(
			'label'       => __( 'Screenshot', 'directories-pro' ),
			'field_types' => array( 'url' ),
		) + parent::_fieldRendererInfo();
		$info['default_settings']['link']     = 'url';
		$info['default_settings']['target']   = '_blank';
		$info['default_settings']['provider'] = '';
		$info['default_settings']['screenshot_width']  = 320;
		$info['default_settings']['screenshot_height'] = 0;

		return $info;
	}

	protected function _fieldRendererSettingsForm( Field\IField $field, array $settings, array $parents = array() ) {
		$form = parent::_fieldRendererSettingsForm( $field, $settings, $parents );
		unset( $form['width'], $form['height'], $form['cols'], $form['gutter_width'] );
		$form['size']['#value']    = 'thumbnail';
		$form['size']['#type']     = 'hidden';
		$form['target']            = array(
			'#title'         => __( 'Open link in', 'directories-pro' ),
			'#type'          => 'select',
			'#options'       => $this->_getLinkTargetOptions(),
			'#default_value' => $settings['target'],
			'#states'        => array(
				'visible' => array(
					sprintf( 'select[name="%s[link]"]', $this->_application->Form_Form_fieldName( $parents ) ) => array( 'value' => 'url' ),
				),
			),
			'#weight'        => 7,
		);
		$form['provider']          = array(
			'#title'         => __( 'Screenshot provider', 'directories-pro' ),
			'#type'          => 'select',
			'#options'       => $this->_application->Filter(
				'directory_screenshot_providers',
				array(
					''        => __( 'WordPress mShots API', 'directories-pro' ),
					'thum.io' => 'thum.io',
				)
			),
			'#weight'        => 1,
			'#default_value' => $settings['provider'],
		);
		$form['screenshot_width']  = array(
			'#title'         => __( 'Screenshot image width', 'directories-pro' ),
			'#type'          => 'slider',
			'#weight'        => 2,
			'#default_value' => $settings['screenshot_width'],
			'#min_value'     => 0,
			'#max_value'     => 1000,
			'#integer'       => true,
			'#step'          => 10,
			'#field_suffix'  => 'px',
		);
		$form['screenshot_height'] = array(
			'#title'         => __( 'Screenshot image height', 'directories-pro' ),
			'#type'          => 'slider',
			'#weight'        => 2,
			'#default_value' => $settings['screenshot_height'],
			'#min_text'      => __( 'Auto', 'directories-pro' ),
			'#min_value'     => 0,
			'#max_value'     => 1000,
			'#integer'       => true,
			'#step'          => 10,
			'#field_suffix'  => 'px',
		);

		return $form;
	}

	protected function _getImageLinkTypeOptions( Entity\Model\Bundle $bundle ) {
		$options = parent::_getImageLinkTypeOptions( $bundle );
		unset( $options['photo'] );
		$options['url'] = __( 'URL', 'directories-pro' );
		return $options;
	}

	protected function _getLinkTarget( Field\IField $field, array $settings ) {
		if ( $settings['link'] === 'url' ) {
			return $settings['target'];
		}

		return parent::_getLinkTarget( $field, $settings );
	}

	protected function _getImageLinkUrl( Field\IField $field, array $settings, $value, $permalinkUrl, $imageUrl ) {
		if ( $settings['link'] === 'url' ) {
			return $value;
		}

		return parent::_getImageLinkUrl( $field, $settings, $value, $permalinkUrl, $imageUrl );
	}

	protected function _getImageUrl( Field\IField $field, array $settings, $value, $size ) {
		$width  = empty( $settings['screenshot_width'] ) || ( ! $width = intval( $settings['screenshot_width'] ) ) ? 320 : $width;
		$height = empty( $settings['screenshot_height'] ) || ( ! $height = intval( $settings['screenshot_height'] ) ) ? 0 : $height;
		try {
			$download = true;
			$url      = $this->_getScreenshotUrl( $settings['provider'] ?? '', $value, $width, $height, $download );
			if ( $download ) {
				$url = $this->_application->getPlatform()->downloadUrl(
					$url,
					function ( &$file ) use ( $settings, $value ) {
						if ( ! $this->_isScreenshotFileValid( $file, $settings, $value ) ) {
							$file = false;
							return false;
						}
						return true;
					},
					trim( preg_replace( '#^https?://#', '', $value ), '/' ) . '-' . $width . 'px',
					'.jpeg'
				);
			}
		} catch ( \Exception $e ) {
			$this->_application->logError( $e->getMessage() );
			return;
		}

		return $url;
	}

	protected function _getImageAlt( Field\IField $field, array $settings, $value ) {
		return $value;
	}

	protected function _getImageTitle( Field\IField $field, array $settings, $value ) {
		return $value;
	}

	protected function _getScreenshotUrl( $provider, $value, $width, $height, &$download ) {
		switch ( $provider ) {
			case 'thum.io':
				$url = 'https://image.thum.io/get/width/' . $width;
				if ( ! empty( $height ) ) {
					$url .= '/crop/' . $height;
				}
				$url     .= '/' . $value;
				$download = false;
				break;
			default:
				$url = 'http://s.wordpress.com/mshots/v1/' . urlencode( $value ) . '?w=' . $width;
				if ( ! empty( $height ) ) {
					$url .= 'h=' . $height;
				}
		}
		return $this->_application->Filter( 'directory_screenshot_url', $url, array( $provider, $value, $width, $height ) );
	}

	protected function _isScreenshotFileValid( $file, array $settings, $value ) {
		$mime = $this->_application->System_Util_fileType( $file );
		return strpos( $mime, 'image/jpeg' ) !== false;
	}
}
