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

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

class TemplateFieldRenderer extends AbstractRenderer {

	protected function _fieldRendererInfo() {
		return array(
			'field_types'      => array( 'fieldset_fieldset' ),
			'label'            => _x( 'Text Template', 'directories-pro' ),
			'default_settings' => array(
				'template' => '',
			),
			'containable'      => false,
		);
	}

	protected function _fieldRendererSettingsForm( IField $field, array $settings, array $parents = array() ) {
		$bundle = $this->_getFieldsetBundle( $field );
		return array(
			'template' => array(
				'#title'                 => __( 'Text Template', 'directories-pro' ),
				'#description'           => $this->_application->System_Util_availableTags( $this->_application->Entity_Tokens( $bundle, true ) ),
				'#description_no_escape' => isset( $desc ),
				'#default_value'         => isset( $settings['template'] ) ? $settings['template'] : '',
				'#rows'                  => 10,
				'#type'                  => 'editor',
			),
		);
	}

	protected function _fieldRendererRenderField( IField $field, array &$settings, IEntity $entity, array $values, ?array $context = null, $more = 0 ) {
		if ( ! isset( $settings['template'] )
			|| $settings['template'] === ''
			|| ( ! $bundle = $this->_getFieldsetBundle( $field ) )
		) {
			return '';
		}

		$entities = $this->_application->Entity_Query( $bundle->entitytype_name, $bundle->name )
			->fieldIsIn( 'id', $values )
			->fetch();
		$ret      = array();
		foreach ( $entities as $e ) {
			$ret[] = $this->_application->Entity_Tokens_replace(
				$settings['template'],
				$e,
				true
			);
		}

		return implode( $settings['_separator'], $ret );
	}

	protected function _getFieldsetBundle( IField $field ) {
		$field_settings = $field->getFieldSettings();
		return ! empty( $field_settings['bundle'] ) && ( $bundle = $this->_application->Entity_Bundle( $field_settings['bundle'] ) ) ? $bundle : null;
	}
}
