<?php
namespace SabaiApps\Directories\Component\Faker\Generator;

use SabaiApps\Directories\Component\Field\IField;
use SabaiApps\Directories\Component\Entity\Model\Bundle;
use SabaiApps\Directories\Component\Entity\Type\IEntity;

class VotingGenerator extends AbstractGenerator {

	protected function _fakerGeneratorInfo() {
		$info = parent::_fakerGeneratorInfo();
		switch ( $this->_name ) {
			case 'voting_vote':
				$info += array(
					'add_probability'  => true,
					'default_settings' => array(
						'count' => array(
							'min' => 0,
							'max' => 100,
						),
					),
				);
				break;
		}

		return $info;
	}

	public function fakerGeneratorSupports( Bundle $bundle, IField $field ) {
		$field_name = $field->getFieldName();
		if ( strpos( $field_name, 'voting_' ) !== 0
			|| $field_name === 'voting_report'
		) {
			return false;
		}

		if ( ! $voting = (array) $this->_application->Entity_BundleTypeInfo( $bundle, 'voting_enable' ) ) {
			return false;
		}

		return in_array( substr( $field->getFieldName(), strlen( 'voting_' ) ), $voting );
	}

	public function fakerGeneratorSettingsForm( IField $field, array $settings, $mode, array $parents = array() ) {
		switch ( $this->_name ) {
			case 'voting_vote':
				$vote_type = substr( $field->getFieldName(), strlen( 'voting_' ) );
				return array(
					'count' => array(
						'#type'          => 'range',
						'#title'         => sprintf(
							__( 'Number of %s to generate', 'directories-pro' ),
							$this->_application->Voting_Types_impl( $vote_type )->votingTypeInfo( 'label' )
						),
						'#description'   => __( 'A random number within this range will be used.', 'directories-pro' ),
						'#integer'       => true,
						'#min_value'     => 0,
						'#max_value'     => 100,
						'#default_value' => $settings['count'],
					),
				);
		}
	}

	public function fakerGeneratorGenerate( IField $field, array $settings, array &$formStorage, ?IEntity $entity = null ) {
		switch ( $this->_name ) {
			case 'voting_vote':
				$count = mt_rand( $settings['count']['min'], $settings['count']['max'] );
				$sum   = 0;
				$type  = substr( $field->getFieldName(), 7/*strlen('voting_')*/ );
				switch ( $type ) {
					case 'rating':
						for ( $i = 0; $i < $count; ++$i ) {
							$sum += mt_rand( 1, 5 );
						}
						break;
					case 'updown':
						$num = array( -1, 1 );
						for ( $i = 0; $i < $count; ++$i ) {
							$sum += $num[ mt_rand( 0, 1 ) ];
						}
						break;
					default:
						$sum = $count;
				}
				return array(
					'name'       => '',
					'count'      => 0,
					'sum'        => 0,
					'count_init' => $count,
					'sum_init'   => $sum,
					'force'      => true,
				);
		}
	}
}
