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

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

class MapCSVImporter extends AbstractImporter implements IWpAllImportImporter {

	public function csvImporterColumns( Field $field ) {
		return array(
			'lat'  => __( 'Latitude', 'directories-pro' ),
			'lng'  => __( 'Longitude', 'directories-pro' ),
			'zoom' => __( 'Zoom Level', 'directories-pro' ),
		);
	}

	public function csvImporterSettingsForm( Field $field, array $settings, $column, $enclosure, array $parents = array() ) {
		return $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();
		foreach ( $values as $value ) {
			$ret[] = array( $column => $value );
		}

		return $ret;
	}

	public function csvWpAllImportImporterAddField( \RapidAddon $addon, Field $field ) {
		$addon->add_title( $field->getFieldLabel() );
		$addon->add_field(
			$field->getFieldName() . '-lat',
			__( 'Latitude', 'directories-pro' ),
			'text',
			null,
			'',
			true,
			''
		);
		$addon->add_field(
			$field->getFieldName() . '-lng',
			__( 'Longitude', 'directories-pro' ),
			'text',
			null,
			'',
			true,
			''
		);
		$addon->add_field(
			$field->getFieldName() . '-zoom',
			__( 'Zoom Level', 'directories-pro' ),
			'text',
			null,
			'',
			true,
			'10'
		);
		return true;
	}

	public function csvWpAllImportImporterDoImport( \RapidAddon $addon, Field $field, array $data, $options, array $article ) {
		if ( empty( $data[ $field->getFieldName() . '-lat' ] )
			|| empty( $data[ $field->getFieldName() . '-lng' ] )
			|| ! is_numeric( $data[ $field->getFieldName() . '-lat' ] )
			|| ! is_numeric( $data[ $field->getFieldName() . '-lng' ] )
		) {
			return;
		}

		$zoom = (int) @$data[ $field->getFieldName() . '-zoom' ];
		if ( ! $zoom < 1 || $zoom > 20 ) {
			$zoom = 10;
		}

		return array(
			array(
				'lat'  => $data[ $field->getFieldName() . '-lat' ],
				'lng'  => $data[ $field->getFieldName() . '-lng' ],
				'zoom' => $zoom,
			),
		);
	}
}
