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

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

class RatingFieldRenderer extends Field\Renderer\AbstractRenderer {

	protected static $_count = 0;

	protected function _fieldRendererInfo() {
		return array(
			'field_types'      => array( 'voting_vote' ),
			'default_settings' => array(
				// 'color' => '#edb867',
				'hide_empty'   => false,
				'hide_count'   => false,
				'read_only'    => false,
				'allow_update' => true,
			),
			'inlineable'       => true,
			'emptiable'        => true,
		);
	}

	public function fieldRendererSupports( Entity\Model\Bundle $bundle, Field\IField $field ) {
		return $field->getFieldName() === 'voting_rating';
	}

	protected function _fieldRendererSettingsForm( Field\IField $field, array $settings, array $parents = array() ) {
		return array(
			// 'color' => [
			// '#type' => 'colorpicker',
			// '#title' => __('Star color', 'directories-pro'),
			// '#default_value' => $settings['color'],
			// '#horizontal' => true,
			// ],
			'hide_empty'   => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Hide if no ratings', 'directories-pro' ),
				'#default_value' => ! empty( $settings['hide_empty'] ),
				'#horizontal'    => true,
			),
			'hide_count'   => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Hide count', 'directories-pro' ),
				'#default_value' => ! empty( $settings['hide_count'] ),
				'#horizontal'    => true,
			),
			'read_only'    => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Read only', 'directories-pro' ),
				'#default_value' => ! empty( $settings['read_only'] ),
				'#horizontal'    => true,
			),
			'allow_update' => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Allow updating rating', 'directories-pro' ),
				'#default_value' => ! empty( $settings['allow_update'] ),
				'#horizontal'    => true,
				'#states'        => array(
					'visible' => array(
						sprintf( '[name="%s"]', $this->_application->Form_Form_fieldName( array_merge( $parents, array( 'read_only' ) ) ) ) => array(
							'type'  => 'checked',
							'value' => false,
						),
					),
				),
			),
		);
	}

	protected function _fieldRendererRenderField( Field\IField $field, array &$settings, Entity\Type\IEntity $entity, array $values, ?array $context = null, $more = 0 ) {
		$current = empty( $values[0][''] ) ? array() : $values[0][''];
		if ( empty( $current['count'] ) ) {
			if ( ! empty( $settings['hide_empty'] ) ) {
				return;
			}

			$current += array(
				'count'   => 0,
				'average' => 0,
			);
		}

		if ( $settings['read_only']
			|| ! $entity->isPublished()
			|| ( empty( $settings['allow_update'] ) && $this->_application->Voting_Votes( $entity->getId(), 'rating' ) )
			|| ! $this->_application->Voting_CanVote( $entity, 'rating' )
		) {
			return $this->_application->Voting_RenderRating( $current['average'], array( 'count' => $settings['hide_count'] ? null : $current['count'] ) );
		}

		$this->_application->getPlatform()
			->addJsFile( 'jquery.barrating.min.js', 'jquery-barrating', array( 'jquery' ), 'directories-pro', true, true )
			->addJsFile( 'voting-rating.min.js', 'drts-voting-rating', array( 'jquery-barrating', 'drts' ), 'directories-pro' );

		$id = 'drts-voting-field-rating-' . ++self::$_count;

		$level   = empty( $current['level'] ) ? 0 : (int) $current['level'];
		$options = array( '<option value=""></option>' ); // required for 0-stars
		for ( $i = 1; $i <= 5; ++$i ) {
			$options[ $i ] = sprintf( '<option value="%1$d"%2$s>%1$d</option>', $i, $level === $i ? ' selected="selected"' : '' );
		}
		$margin_x_class = DRTS_BS_PREFIX . 'ms-1';

		return sprintf(
			'<div class="drts-voting-rating"><span class="drts-voting-rating-select" id="%1$s" data-vote-url="%3$s" data-vote-rating="%6$d"><select style="display:none;">%2$s</select></span><span class="drts-voting-rating-average %7$s">%4$04.2f</span>%5$s</div>
',
			$id,
			implode( PHP_EOL, $options ),
			$this->_application->Url(
				'/_drts/voting/vote',
				array(
					'entity_type'               => $entity->getType(),
					'entity_id'                 => $entity->getId(),
					'voting_type'               => 'rating',
					Request::PARAM_CONTENT_TYPE => 'json',
					Request::PARAM_TOKEN        => $this->_application->Form_Form_createToken( 'voting_vote_entity', 3600, true ),
				),
				'',
				'&'
			),
			$current['average'],
			$settings['hide_count'] ? '' : '<span class="drts-voting-rating-count ' . $margin_x_class . '">' . intval( $current['count'] ) . '</span>',
			$level,
			$margin_x_class
		);
	}

	public function fieldRendererIsPreRenderable( Field\IField $field, array $settings ) {
		return true;
	}

	public function fieldRendererPreRender( Field\IField $field, array $settings, array $entities = array() ) {
		if ( empty( $entities ) ) {
			return;
		}

		$this->_application->Voting_Votes_load( $field->Bundle->name, array_keys( $entities ) );
	}

	protected function _fieldRendererReadableSettings( Field\IField $field, array $settings ) {
		return array(
			'hide_empty' => array(
				'label'   => __( 'Hide if no ratings', 'directories-pro' ),
				'value'   => ! empty( $settings['hide_empty'] ),
				'is_bool' => true,
			),
			'hide_count' => array(
				'label'   => __( 'Hide count', 'directories-pro' ),
				'value'   => ! empty( $settings['hide_count'] ),
				'is_bool' => true,
			),
			'read_only'  => array(
				'label'   => __( 'Read only', 'directories-pro' ),
				'value'   => ! empty( $settings['read_only'] ),
				'is_bool' => true,
			),
		);
	}
}
