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

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

class EntityCSVImporter extends AbstractImporter implements IWpAllImportImporter {

	protected $_parentBundle;

	public function csvImporterColumns( Field $field ) {
		switch ( $this->_name ) {
			case 'entity_featured':
				return array(
					'value'       => __( 'Priority', 'directories-pro' ),
					'featured_at' => __( 'Featured Date', 'directories-pro' ),
					'expires_at'  => __( 'End Date', 'directories-pro' ),
				);
			case 'entity_activity':
				return array(
					'active_at' => __( 'Last Active Date', 'directories-pro' ),
					'edited_at' => __( 'Edited Date', 'directories-pro' ),
				);
		}
		return parent::csvImporterColumns( $field );
	}

	public function csvImporterSupports( Bundle $bundle, Field $field ) {
		switch ( $this->_name ) {
			case 'entity_post_views':
				return empty( $bundle->info['parent'] ) && empty( $bundle->info['parent_field'] ) && ! empty( $bundle->info['public'] );
			case 'entity_slug':
				return empty( $bundle->info['parent'] ) && empty( $bundle->info['parent_field'] );
			case 'entity_term_parent':
				return ! empty( $bundle->info['is_hierarchical'] );
		}
		return true;
	}

	public function csvImporterSettingsForm( Field $field, array $settings, $column, $enclosure, array $parents = array() ) {
		switch ( $this->_name ) {
			case 'entity_published':
				return $this->_getDateFormatSettingsForm( $parents );
			case 'entity_author':
				return $this->_getUserSettingsForm();
			case 'entity_featured':
				return in_array( $column, array( 'featured_at', 'expires_at' ) ) ? $this->_getDateFormatSettingsForm( $parents ) : null;
			case 'entity_activity':
				return in_array( $column, array( 'active_at', 'edited_at' ) ) ? $this->_getDateFormatSettingsForm( $parents ) : null;
			case 'entity_child_count':
				return array(
					'separator' => array(
						'#type'          => 'textfield',
						'#title'         => $title = __( 'Content type/count separator', 'directories-pro' ),
						'#description'   => __( 'Enter the character used to separate the content type and count.', 'directories-pro' ),
						'#default_value' => '|',
						'#horizontal'    => true,
						'#min_length'    => 1,
						'#required'      => true,
						'#weight'        => 1,
					),
				) + $this->_acceptMultipleValues( $field, $enclosure, $parents, array( 'separator' => $title ) );
			case 'entity_parent':
				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,
					),
				);
			case 'entity_term_parent':
				return array(
					'type' => array(
						'#type'          => 'select',
						'#title'         => __( 'Parent term data type', 'directories-pro' ),
						'#description'   => __( 'Select the type of data used to specify terms.', 'directories-pro' ),
						'#options'       => array(
							'id'    => __( 'ID', 'directories-pro' ),
							'slug'  => __( 'Slug', 'directories-pro' ),
							'title' => __( 'Title', 'directories-pro' ),
						),
						'#default_value' => 'slug',
						'#horizontal'    => true,
					),
				);
			case 'entity_term_content_count':
				return array(
					'separator' => array(
						'#type'          => 'textfield',
						'#title'         => $sep_title = __( 'Content type/count separator', 'directories-pro' ),
						'#description'   => __( 'Enter the character used to separate the content type and count.', 'directories-pro' ),
						'#default_value' => '|',
						'#horizontal'    => true,
						'#min_length'    => 1,
						'#required'      => true,
						'#weight'        => 1,
					),
				) + $this->_acceptMultipleValues( $field, $enclosure, $parents, array( 'separator' => $sep_title ) );
		}
	}

	public function csvImporterDoImport( Field $field, array $settings, $column, $value, &$formStorage, array &$logs ) {
		switch ( $this->_name ) {
			case 'entity_published':
				return false !== ( $value = $this->_strToTime( $value, $settings, true ) ) ? $value : null;
			case 'entity_author':
				if ( $settings['id_format'] === 'username' ) {
					$value = $this->_application->getPlatform()->getUserIdentityFetcher()->fetchByUsername( $value )->id;
				}
				return $value;
			case 'entity_featured':
				if ( in_array( $column, array( 'featured_at', 'expires_at' ) ) ) {
					if ( false === $value = $this->_strToTime( $value, $settings ) ) {
						return null;
					}
				}
				return array( array( $column => $value ) );
			case 'entity_activity':
				if ( in_array( $column, array( 'active_at', 'edited_at' ) ) ) {
					if ( false === $value = $this->_strToTime( $value, $settings ) ) {
						return null;
					}
				}
				return array( array( $column => $value ) );
			case 'entity_child_count':
				if ( ! empty( $settings['_multiple'] ) ) {
					if ( ! $values = explode( $settings['_separator'], $value ) ) {
						return;
					}
				} else {
					$values = array( $value );
				}
				$ret = array();
				foreach ( $values as $value ) {
					if ( $value = explode( $settings['separator'], $value ) ) {
						$ret[] = array(
							'child_bundle_name' => $value[0],
							'value'             => $value[1],
						);
					}
				}
				return $ret;
			case 'entity_parent':
				if ( $settings['type'] === 'slug' ) {
					if ( ! isset( $this->_parentBundle )
						&& ( ! $this->_parentBundle = $this->_application->Entity_Bundle( $field->Bundle->info['parent'] ) )
					) {
						return false;
					}

					if ( ! $entity = $this->_application->Entity_Types_impl( $this->_parentBundle->entitytype_name )
						->entityTypeEntityBySlug( $this->_parentBundle->name, $value )
					) {
						return;
					}

					return $entity->getId();
				} else {
					return $value;
				}
			case 'entity_term_parent':
				switch ( $settings['type'] ) {
					case 'slug':
						$bundle = $field->Bundle;
						if ( ! $term = $this->_application->Entity_Types_impl( $bundle->entitytype_name )->entityTypeEntityBySlug( $bundle->name, $value ) ) {
							return;
						}

						return $term->getId();
					case 'title':
						$bundle = $field->Bundle;
						if ( ! $term = $this->_application->Entity_Types_impl( $bundle->entitytype_name )->entityTypeEntityByTitle( $bundle->name, $value ) ) {
							return;
						}

						return $term->getId();
					default:
						return $value;
				}
			case 'entity_term_content_count':
				if ( ! empty( $settings['_multiple'] ) ) {
					if ( ! $values = explode( $settings['_separator'], $value ) ) {
						return;
					}
				} else {
					$values = array( $value );
				}
				$ret = array();
				foreach ( $values as $value ) {
					if ( $value = explode( $settings['separator'], $value ) ) {
						$ret[] = array(
							'content_bundle_name' => $value[0],
							'value'               => $value[1],
							'merged'              => $value[2],
						);
					}
				}
				return $ret;
			default:
				return $value;
		}
	}

	public function csvWpAllImportImporterAddField( \RapidAddon $addon, Field $field ) {
		switch ( $this->_name ) {
			case 'entity_featured':
				$addon->add_title( $field->getFieldLabel() );
				$addon->add_field(
					$field->getFieldName(),
					'',
					'radio',
					array(
						1 => array(
							__( 'Yes', 'directories-pro' ),
							$addon->add_field( $field->getFieldName() . '-expires_at', __( 'End date', 'directories-pro' ), 'text' ),
							$addon->add_field(
								$field->getFieldName() . '-priority',
								__( 'Priority', 'directories-pro' ),
								'radio',
								array(
									9 => __( 'High', 'directories-pro' ),
									5 => __( 'Normal', 'directories-pro' ),
									1 => __( 'Low', 'directories-pro' ),
								),
								'',
								true,
								5
							),
						),
						0 => __( 'No', 'directories-pro' ),
					),
					'',
					true,
					0
				);
				return true;
		}
	}

	public function csvWpAllImportImporterDoImport( \RapidAddon $addon, Field $field, array $data, $options, array $article ) {
		switch ( $this->_name ) {
			case 'entity_featured':
				if ( empty( $data[ $field->getFieldName() ] ) ) {
					return;
				}

				if ( ! isset( $data[ $field->getFieldName() . '-priority' ] ) || ! in_array( $priority = $data[ $field->getFieldName() . '-priority' ], array( 1, 9 ) ) ) {
					$priority = 5;
				}
				if ( empty( $data[ $field->getFieldName() . '-expires_at' ] ) ) {
					$expires_at = 0;
				} else {
					if ( is_numeric( $data[ $field->getFieldName() . '-expires_at' ] ) ) {
						$expires_at = $data[ $field->getFieldName() . '-expires_at' ];
					} elseif ( ! $expires_at = $this->_strToTime( $data[ $field->getFieldName() . '-expires_at' ] ) ) {
						return;
					}
					if ( $expires_at < time() ) {
						return;
					}
				}
				return array(
					array(
						'value'      => $priority,
						'expires_at' => $expires_at,
					),
				);
		}
	}
}
