<?php
namespace SabaiApps\Directories\Component\Entity\CSVImporter;

use SabaiApps\Directories\Component\CSV\Importer\AbstractImporter;
use SabaiApps\Directories\Component\Entity\Model\Field;

class ReferenceCSVImporter extends AbstractImporter {

	public function csvImporterSettingsForm( Field $field, array $settings, $column, $enclosure, array $parents = array() ) {
		return array(
			'type' => array(
				'#type'          => 'select',
				'#title'         => __( 'Content item ID type', 'directories-pro' ),
				'#description'   => __( 'Select the type of data used to specify imported items.', 'directories-pro' ),
				'#options'       => array(
					'id'   => __( 'ID', 'directories-pro' ),
					'slug' => __( 'Slug', 'directories-pro' ),
				),
				'#default_value' => 'slug',
				'#horizontal'    => true,
			),
		) + $this->_acceptMultipleValues( $field, $enclosure, $parents );
	}

	public function csvImporterDoImport( Field $field, array $settings, $column, $value, &$formStorage, array &$logs ) {
		if ( ! empty( $settings['_multiple'] ) ) {
			if ( ! $values = explode( $settings['_separator'], $value ) ) {
				return;
			}
		} else {
			$values = array( $value );
		}
		$ret = array();
		switch ( $settings['type'] ) {
			case 'slug':
				$field_settings = $field->getFieldSettings();
				if ( empty( $field_settings['bundle'] )
					|| ( ! $bundle = $this->_application->Entity_Bundle( $field_settings['bundle'] ) )
				) {
					return;
				}

				$entities = $this->_application->Entity_Types_impl( $bundle->entitytype_name )->entityTypeEntitiesBySlugs( $bundle->name, $values );
				foreach ( $entities as $entity ) {
					$ret[] = $entity->getId();
				}
				break;
			case 'id':
				$ret = $values;
				break;
		}
		return $ret;
	}
}
