<?php
namespace SabaiApps\Directories\Component\Display\Icon;

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

class CustomImage extends AbstractIcon {

	protected function _displayIconInfo( Bundle $bundle ) {
		$info = array(
			'label'            => __( 'Custom image', 'directories-pro' ),
			'default_settings' => array(
				'image'      => null,
				'conditions' => array(),
			),
			'iconable'         => false,
			'colorable'        => false,
		);
		foreach ( $this->_application->Filter( 'entity_icon_custom_image_num', range( 1, 3 ), array( $bundle ) ) as $num ) {
			$info['multiple'][ $num ] = array(
				'default_checked' => $num === 1,
				'label'           => sprintf( __( 'Custom image #%d', 'directories-pro' ), $num ),
			);
		}
		return $info;
	}

	public function displayIconSettingsForm( Bundle $bundle, array $settings, Display $display, array $parents = array() ) {
		$form = array(
			'conditions' => $this->_application->Entity_Field_conditionSettingsForm(
				$bundle->name,
				empty( $settings['conditions'] ) ? array() : $settings['conditions'],
				array_merge( $parents, array( 'conditions' ) ),
				true
			),
			'image'      => array(
				'#title'             => __( 'Image', 'directories-pro' ),
				'#type'              => 'wp_media_manager',
				'#allow_only_images' => true,
				'#max_num_files'     => 1,
				'#horizontal'        => true,
				'#default_value'     => $settings['image'],
				'#weight'            => -3,
			),
		);
		return $form;
	}

	public function displayIconOutput( Bundle $bundle, IEntity $entity, array $settings ) {
		if ( ! empty( $settings['conditions'] )
			&& ! $this->_application->Entity_Field_checkConditions( $settings['conditions'], $entity )
		) {
			return;
		}

		if ( empty( $settings['image'][0] )
			|| ( ! $url = wp_get_attachment_url( $settings['image'][0] ) )
		) {
			return;
		}

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