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

use SabaiApps\Directories\Component\Entity;
use SabaiApps\Directories\Component\Field;

class TermContentCountFieldRenderer extends Field\Renderer\AbstractRenderer {

	protected function _fieldRendererInfo() {
		return array(
			'field_types'      => array( $this->_name ),
			'default_settings' => array(
				'content_bundle_type' => null,
			),
			'inlineable'       => true,
		);
	}

	protected function _fieldRendererSettingsForm( Field\IField $field, array $settings, array $parents = array() ) {
		$form = array();
		if ( ( $content_bundle_name = $this->_application->Entity_TaxonomyContentBundleTypes( $field->Bundle->type, $field->Bundle->group ) )
			&& ( $content_bundle = $this->_application->Entity_Bundle( $content_bundle_name ) )
		) {
			$form['content_bundle_type'] = array(
				'#type'          => 'hidden',
				'#default_value' => $content_bundle->type,
			);
		}

		return $form;
	}

	protected function _fieldRendererRenderField( Field\IField $field, array &$settings, Entity\Type\IEntity $entity, array $values, ?array $context = null, $more = 0 ) {
		if ( ! empty( $settings['content_bundle_type'] )
			&& ( $taxonomy_bundle = isset( $context['original_taxonomy_bundle'] ) ? $context['original_taxonomy_bundle'] : $field->Bundle )
			&& ( $content_bundle = $this->_application->Entity_Bundle( $settings['content_bundle_type'], $taxonomy_bundle->group ) )
			&& ( $count = (int) $entity->getSingleFieldValue( $field->getFieldName(), '_' . $content_bundle->name ) )
		) {
			return sprintf( _n( $content_bundle->getLabel( 'count' ), $content_bundle->getLabel( 'count2' ), $count, 'directories-pro' ), $count );
		}
	}
}
