<?php
namespace SabaiApps\Directories\Component\Entity\DisplayElement;

use SabaiApps\Directories\Component\Entity\Model\Bundle;
use SabaiApps\Directories\Exception;
use SabaiApps\Directories\Component\Display\Model\Display;

class ReferenceFieldDisplayElement extends FieldDisplayElement {

	protected $_fieldName;
	protected $_refBundleName;
	protected $_refBundleFieldName;

	public function __construct( $application, $name ) {
		parent::__construct( $application, $name );

		// Extract referenced bundle name from the display element name
		$parts = explode( '__', substr( $name, 23 ) ); // remove entity_reference_field_ part
		if ( count( $parts ) !== 3 ) {
			throw new Exception\RuntimeException( 'Invalid reference field display element name' );
		}
		$this->_fieldName          = $parts[0];
		$this->_refBundleName      = $parts[1];
		$this->_refBundleFieldName = $parts[2];
	}

	protected function _doGetField( $bundle ) {
		if ( ! $ref_bundle = $this->_application->Entity_Bundle( $this->_refBundleName ) ) {
			throw new Exception\RuntimeException( 'Invalid entity parent bundle' );
		}
		return $this->_application->Entity_Field( $ref_bundle, $this->_refBundleFieldName );
	}

	protected function _displayElementSupports( Bundle $bundle, Display $display ) {
		return $display->type === 'entity';
	}

	protected function _displayElementInfo( Bundle $bundle ) {
		$field            = $this->_application->Entity_Field( $bundle, $this->_fieldName );
		$ref_bundle_field = $this->_getField( $bundle );

		return array(
			'type'             => 'field',
			'label'            => $field->getFieldLabel() . ' - ' . $ref_bundle_field->getFieldLabel(),
			'description'      => sprintf( __( 'Field name: %s', 'directories-pro' ), $ref_bundle_field->getFieldName() ),
			'class'            => 'drts-field-type-' . str_replace( '_', '-', $ref_bundle_field->getFieldType() ) . ' drts-field-name-' . str_replace( '_', '-', $ref_bundle_field->getFieldName() ),
			'default_settings' => array(
				'label'             => 'none',
				'label_custom'      => null,
				'label_icon'        => null,
				'label_icon_size'   => null,
				'renderer'          => null,
				'renderer_settings' => array(),
			),
			'icon'             => $this->_application->Field_Type( $field->getFieldType() )->fieldTypeInfo( 'icon' ),
			'headingable'      => false,
			'cacheable'        => $this->_application->Field_Type( $field->getFieldType() )->fieldTypeInfo( 'cacheable' ),
			'designable'       => array( 'margin', 'font' ),
		);
	}

	public function displayElementRender( Bundle $bundle, array $element, $var, ?array $context = null ) {
		if ( ! $entity = $var->getSingleFieldValue( $this->_fieldName ) ) {
			return;
		}

		$this->_application->Entity_Field_load( $entity );
		return parent::displayElementRender( $bundle, $element, $entity, $context );
	}

	public function displayElementPreRender( Bundle $bundle, array $element, &$var ) {
		$entities = array();
		if ( ! empty( $var['entities'] ) ) {
			foreach ( $var['entities'] as $entity ) {
				if ( $_entity = $entity->getSingleFieldValue( $this->_fieldName ) ) {
					$entities[ $_entity->getId() ] = $_entity;
				}
			}
		}
		$_var['entities'] = $entities;
		parent::displayElementPreRender( $bundle, $element, $_var );
	}

	public function displayElementTitle( Bundle $bundle, array $data ) {
		$ref_bundle_field = $this->_getField( $bundle );
		return $this->_application->Display_Render_elementLabel(
			$data['settings'],
			null,
			$this->_application->Entity_Field( $bundle, $this->_fieldName )->getFieldLabel() . ' - ' . $ref_bundle_field->getFieldLabel()
		);
	}
}
