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

use SabaiApps\Directories\Component\Display;
use SabaiApps\Directories\Application;
use SabaiApps\Directories\Component\Entity\Model\Bundle;
use SabaiApps\Directories\Component\Entity\Type\IEntity;

class PostCountDisplayStatistic extends Display\Statistic\AbstractStatistic {

	protected $_bundleName;

	public function __construct( Application $application, $name ) {
		parent::__construct( $application, $name );
		$this->_bundleName = substr( $this->_name, 10 ); // remove user_post_ prefix
	}

	protected function _displayStatisticInfo( Bundle $bundle ) {
		if ( ! $post_bundle = $this->_application->Entity_Bundle( $this->_bundleName ) ) {
			return;
		}

		return array(
			'label'            => __( 'Post count', 'drts' ) . ' - ' . $post_bundle->getLabel(),
			'default_settings' => array(),
			'iconable'         => false,
		);
	}

	public function displayStatisticRender( Bundle $bundle, IEntity $entity, array $settings ) {
		if ( ! $post_bundle = $this->_application->Entity_Bundle( $this->_bundleName ) ) {
			return;
		}

		$number = 0;
		if ( ( $counts = $entity->getSingleFieldValue( 'user_post_count', $post_bundle->type ) )
			&& ! empty( $counts[ $post_bundle->name ] )
		) {
			if ( ! $lang = $this->_application->getPlatform()->getCurrentLanguage() ) {
				$lang = '';
			}
			if ( isset( $counts[ $post_bundle->name ][ $lang ] ) ) {
				$number = (int) $counts[ $post_bundle->name ][ $lang ];
			}
		}
		return array(
			'number' => $number,
			'format' => $number === 1 ? $post_bundle->getLabel( 'count' ) : $post_bundle->getLabel( 'count2' ),
			'icon'   => $this->_application->Entity_BundleTypeInfo( $post_bundle, 'icon' ),
		);
	}
}
