<?php
namespace SabaiApps\Directories\Component\System\Tool;

use SabaiApps\Directories\Context;
use SabaiApps\Directories\Exception;

/**
 * AbstractImportJsonTool provides a base class for tools that import data in JSON format.
 */
abstract class AbstractImportJsonTool extends AbstractTool {

	public function systemToolSettingsForm( $step, array $values, array $parents = array(), ?Context $context = null ) {
		return array(
			'import_method' => array(
				'#title'         => __( 'Import method', 'directories-pro' ),
				'#type'          => 'radios',
				'#options'       => array(
					'file' => __( 'Upload JSON file', 'directories-pro' ),
					'text' => __( 'Paste JSON data', 'directories-pro' ),
				),
				'#default_value' => 'file',
				'#horizontal'    => true,
			),
			'json_file'     => array(
				'#type'               => 'file',
				'#title'              => __( 'JSON file', 'directories-pro' ),
				'#upload_dir'         => $this->_application->getComponent( 'System' )->getTmpDir(),
				'#allowed_extensions' => array( 'json' ),
				'#required'           => true,
				'#multiple'           => false,
				'#horizontal'         => true,
				'#states'             => array(
					'visible' => array(
						$import_method_selector = sprintf( '[name="%s"]', $this->_application->Form_Form_fieldName( array( $parents, 'import_method' ) ) ) => array( 'value' => 'file' ),
					),
				),
			),
			'json_text'     => array(
				'#type'          => 'textarea',
				'#title'         => __( 'Or paste JSON data', 'directories-pro' ),
				'#description'   => __( 'You can either upload a JSON file or paste JSON data into the text area above.', 'directories-pro' ),
				'#default_value' => '',
				'#rows'          => 10,
				'#horizontal'    => true,
				'#states'        => array(
					'visible' => array(
						$import_method_selector => array( 'value' => 'text' ),
					),
				),
			),
		);
	}

	public function systemToolRunTask( $task, array $settings, $iteration, $total, array &$storage, array &$logs, ?Context $context = null ) {
		if ( $settings['import_method'] === 'file' ) {
			if ( empty( $settings['json_file']['saved_file_path'] )
				|| false === ( $json = file_get_contents( $settings['json_file']['saved_file_path'] ) )
			) {
				throw new Exception\RuntimeException( __( 'JSON configuration file was not uploaded.', 'directories-pro' ) );
			}
		} else {
			$json = $settings['json_text'];
		}
		if ( ! $decoded = json_decode( $json, true ) ) {
			throw new Exception\RuntimeException( __( 'Invalid JSON data', 'directories-pro' ) );
		}

		$this->_import( $decoded, $logs, $context );

		return 1;
	}

	abstract protected function _import( array $data, array &$logs, ?Context $context = null );
}
