<?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 CountFieldRenderer extends AbstractRenderer {

	protected function _fieldRendererInfo() {
		return array(
			'field_types'      => array( 'fieldset_fieldset' ),
			'label'            => _x( 'Count', 'number of items added by fieldset field', 'directories-pro' ),
			'default_settings' => array(),
			'separatable'      => false,
			'containable'      => false,
		);
	}

	protected function _fieldRendererSettingsForm( IField $field, array $settings, array $parents = array() ) {
		if ( ! $bundle = $this->_getFieldsetBundle( $field ) ) {
			return;
		}

		return array();
	}

	protected function _fieldRendererRenderField( IField $field, array &$settings, IEntity $entity, array $values, ?array $context = null, $more = 0 ) {
		if ( empty( $values ) ) {
			return;
		}

		if ( ! $bundle = $this->_getFieldsetBundle( $field ) ) {
			return;
		}

		$count = $this->_application->Entity_Query( $bundle->entitytype_name, $bundle->name )
			->fieldIsIn( $bundle->entitytype_name . '_id', $values )
			->count();
		return sprintf( _n( $bundle->getLabel( 'count' ), $bundle->getLabel( 'count2' ), $count, 'directories-pro' ), $count );
	}

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

	protected function _fieldRendererReadableSettings( IField $field, array $settings ) {
		return array();
	}
}
