<?php
namespace SabaiApps\Directories\Component\View\DisplayIcon;

use SabaiApps\Directories\Component\Display;
use SabaiApps\Directories\Component\Entity\Model\Bundle;
use SabaiApps\Directories\Component\Entity\Type\IEntity;

class TopRankingImageDisplayIcon extends Display\Icon\AbstractIcon {

	protected static $_maxNum = 5;

	protected function _displayIconInfo( Bundle $bundle ) {
		return array(
			'label'            => __( 'Top ranking image', 'directories-pro' ),
			'default_settings' => array(
				'conditions' => array(),
				'images'     => array(),
			),
			'iconable'         => false,
			'colorable'        => false,
			'linkable'         => false,
			'weight'           => 30,
		);
	}

	public function displayIconSupports( Bundle $bundle, Display\Model\Display $display ) {
		return strpos( $display->name, 'summary' ) === 0;
	}

	public function displayIconSettingsForm( Bundle $bundle, array $settings, Display\Model\Display $display, array $parents = array() ) {
		$form = array(
			'#description' => sprintf( __( 'Displays an icon for the first %d listings in "List" view mode.', 'directories-pro' ), self::$_maxNum ),
			'conditions'   => $this->_application->Entity_Field_conditionSettingsForm(
				$bundle->name,
				empty( $settings['conditions'] ) ? array() : $settings['conditions'],
				array_merge( $parents, array( 'conditions' ) ),
				true
			),
			'images'       => array(
				'#title'             => __( 'Ranking images', 'directories-pro' ),
				'#description'       => __( 'The images in the table will be used in the order from top to bottom. You can change the order of the images in the table by dragging them.' ),
				'#type'              => 'wp_media_manager',
				'#allow_only_images' => true,
				'#multiple'          => true,
				'#max_num_files'     => self::$_maxNum,
				'#horizontal'        => true,
				'#default_value'     => $settings['images'],
				'#weight'            => -3,
				'#sortable'          => true,
			),
		);

		return $form;
	}

	public function displayIconOutput( Bundle $bundle, IEntity $entity, array $settings ) {
		if ( empty( $entity->data['view_list_entity_order'] )
			|| ( ! $rank = (int) $entity->data['view_list_entity_order'] )
			|| $rank > self::$_maxNum
			|| empty( $settings['images'][ $rank - 1 ] )
		) {
			return;
		}

		if ( ! empty( $settings['conditions'] )
			&& ! $this->_application->Entity_Field_checkConditions( $settings['conditions'], $entity )
		) {
			return;
		}

		if ( ! $url = wp_get_attachment_url( $settings['images'][ $rank - 1 ] ) ) {
			return;
		}

		return array( 'icon' => $url );
	}
}
