<?php
namespace SabaiApps\Directories\Component\Fieldset\FakerGenerator;

use SabaiApps\Directories\Component\Field\IField;
use SabaiApps\Directories\Component\Faker\Generator\AbstractGenerator;
use SabaiApps\Directories\Component\Entity\Type\IEntity;

class FieldsetFakerGenerator extends AbstractGenerator {

	protected function _fakerGeneratorInfo() {
		$info  = parent::_fakerGeneratorInfo();
		$info += array(
			'add_probability'  => true,
			'default_settings' => array(
				'max'         => 5,
				'probability' => 70,
			),
		);

		return $info;
	}

	public function fakerGeneratorSettingsForm( IField $field, array $settings, $mode, array $parents = array() ) {
		$field_settings = $field->getFieldSettings();
		if ( empty( $field_settings['bundle'] )
			|| ( ! $bundle = $this->_application->Entity_Bundle( $field_settings['bundle'] ) )
			|| ( ! $fieldset_fields = $this->_application->Entity_Field( $bundle->name ) )
		) {
			return;
		}

		$form = array( 'max' => $this->_getMaxNumItemsSettingForm( $field, $settings['max'] ) );
		foreach ( $fieldset_fields as $f_field ) {
			if ( ( $property = $f_field->isPropertyField() )
				&& in_array( $property, array( 'published', 'title', 'content' ) )
			) {
				continue;
			}

			$f_field_name     = $f_field->getFieldName();
			$f_field_settings = $this->_application->Faker_Generators_settingsForm( $f_field, $mode, array_merge( $parents, array( $f_field_name ) ), false );
			if ( ! empty( $f_field_settings ) ) {
				$form[ $f_field_name ] = $f_field_settings;
			}
		}

		return $form;
	}

	public function fakerGeneratorGenerate( IField $field, array $settings, array &$formStorage, ?IEntity $entity = null ) {
		$field_settings = $field->getFieldSettings();
		if ( empty( $field_settings['bundle'] )
			|| ( ! $bundle = $this->_application->Entity_Bundle( $field_settings['bundle'] ) )
			|| ( ! $fieldset_fields = $this->_application->Entity_Field( $bundle->name ) )
		) {
			return;
		}

		$formStorage[ $field->getFieldName() ] = array();
		$ret                                   = array();
		$count                                 = $this->_getMaxNumItems( $field, $settings['max'] );
		for ( $i = 0; $i < $count; ++$i ) {
			foreach ( $fieldset_fields as $f_field ) {
				$f_field_name = $f_field->getFieldName();
				if ( $f_field->getFieldType() === 'entity_published' ) {
					$generated = time();
				} else {
					$generated = $this->_application->Faker_Generators_generate( $f_field, $settings[ $f_field_name ] ?? array(), $formStorage[ $field->getFieldName() ] );
					if ( $generated === null ) {
						continue;
					}
					if ( $generated === false ) {
						return false;
					}
				}
				$ret[ $i ][ $f_field_name ] = $generated;
			}
		}

		return empty( $ret ) ? null : $ret;
	}
}
