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

use SabaiApps\Directories\Component\Field\Renderer\AbstractRenderer;
use SabaiApps\Directories\Component\Entity\Type\IEntity;
use SabaiApps\Directories\Component\Field\IField;

class AuthorCardFieldRenderer extends AbstractRenderer {

	protected function _fieldRendererInfo() {
		return array(
			'label'            => __( 'Author card', 'directories-pro' ),
			'field_types'      => array( 'entity_author' ),
			'default_settings' => array(
				'card_width'     => 100,
				'subtitle_field' => null,
			),
		);
	}

	protected function _fieldRendererSettingsForm( IField $field, array $settings, array $parents = array() ) {
		$subtitle_fields = $this->_application->Entity_Field_options(
			'users_usr_usr',
			array(
				'interface'       => 'Field\Type\IHumanReadable',
				'return_disabled' => true,
			)
		);
		return array(
			'card_width'     => array(
				'#type'          => 'slider',
				'#title'         => __( 'Card width', 'directories-pro' ),
				'#default_value' => $settings['card_width'],
				'#horizontal'    => true,
				'#min_value'     => 100,
				'#max_value'     => 10,
				'#field_suffix'  => '%',
			),
			'subtitle_field' => array(
				'#type'             => 'select',
				'#title'            => $title = __( 'Subtitle field', 'directories-pro' ),
				'#options'          => array( '' => '— ' . __( 'Select field', 'directories-pro' ) . ' —' ) + $subtitle_fields[0],
				'#options_disabled' => array_keys( $subtitle_fields[1] ),
				'#default_value'    => $settings['subtitle_field'],
				'#horizontal'       => true,
			),
		);
	}

	protected function _fieldRendererRenderField( IField $field, array &$settings, IEntity $entity, array $values, ?array $context = null, $more = 0 ) {
		if ( ( ! $user_id = $entity->getAuthorId() )
			|| ( ! $user = $this->_application->Entity_Entity( 'user', $user_id ) )
		) {
			return;
		}

		return $this->_application->Entity_Card(
			$user,
			array(
				'width'           => $settings['card_width'],
				'cover_field'     => 'user_photos',
				'thumbnail_field' => 'user_photo',
				'title_field'     => 'user_name',
				'subtitle_field'  => $settings['subtitle_field'],
				'content'         => $this->_application->System_Text_summarize( $user->getContent(), 100 ),
			)
		);
	}

	public function fieldRendererIsPreRenderable( IField $field, array $settings ) {
		return true;
	}

	public function fieldRendererPreRender( IField $field, array $settings, array $entities = array() ) {
		if ( empty( $entities ) ) {
			return;
		}

		$user_ids = array();
		foreach ( array_keys( $entities ) as $entity_id ) {
			if ( $user_id = $entities[ $entity_id ]->getAuthorId() ) {
				$user_ids[] = $user_id;
			}
		}
		$this->_application->Entity_Entities( 'user', $user_ids );
	}
}
