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

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

class FileGenerator extends AbstractGenerator {

	protected $_ids, $_idCount;

	protected function _fakerGeneratorInfo() {
		$info                     = parent::_fakerGeneratorInfo();
		$info['add_probability']  = true;
		$info['default_settings'] = array(
			'max' => null,
		);
		return $info;
	}

	public function fakerGeneratorSettingsForm( IField $field, array $settings, $mode, array $parents = array() ) {
		switch ( $this->_name ) {
			case 'file_image':
			case 'file_file':
				return array(
					'max' => $this->_getMaxNumItemsSettingForm( $field, $settings['max'] ),
				) + $this->_application->File_LocationSettingsForm( $parents );
		}
	}

	public function fakerGeneratorGenerate( IField $field, array $settings, array &$formStorage, ?IEntity $entity = null ) {
		switch ( $this->_name ) {
			case 'file_image':
			case 'file_file':
				$ret   = array();
				$count = $this->_getMaxNumItems( $field, $settings['max'] );
				if ( ! isset( $this->_ids ) ) {
					if ( $settings['location'] === 'none' ) {
						$ids = $this->_application->File_LocationSettingsForm_saveFiles(
							$settings,
							null,
							array( 'image_only' => $this->_name === 'file_image' )
						);
					} else {
						if ( ! isset( $this->_fileDir ) ) {
							$this->_fileDir = $this->_application->File_LocationSettingsForm_uploadDir( $settings );
						}
						if ( ! $this->_fileDir ) {
							return false; // will skip this field
						}

						$files = $this->_application->File_LocationSettingsForm_saveFiles(
							$settings,
							null,
							array( 'image_only' => $this->_name === 'file_image' ),
							$this->_fileDir
						);
						$ids   = array_keys( $files );
					}
					$this->_ids     = array_keys( $ids );
					$this->_idCount = count( $this->_ids );
				}
				if ( $this->_idCount > 0 ) {
					$max_index = $this->_idCount - 1;
					for ( $i = 0; $i < $count; ++$i ) {
						$ret[] = array( 'id' => $this->_ids[ mt_rand( 0, $max_index ) ] );
					}
				}

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