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

use SabaiApps\Directories\Application;
use SabaiApps\Directories\Context;

/**
 * AbstractTool provides a base class for system tools.
 * Implements common logic for tool info, settings, and task execution.
 */
abstract class AbstractTool implements ITool {

	protected $_application, $_name, $_info;

	/**
	 * Constructor.
	 *
	 * @param Application $application
	 * @param string      $name
	 */
	public function __construct( Application $application, $name ) {
		$this->_application = $application;
		$this->_name        = $name;
	}

	/**
	 * Returns the tool name.
	 *
	 * @return string
	 */
	public function __toString() {
		return $this->_name;
	}

	/**
	 * Returns tool information as an array, or a specific key if provided.
	 *
	 * @param string|null $key
	 * @return mixed
	 */
	public function systemToolInfo( $key = null ) {
		if ( ! isset( $this->_info ) ) {
			$this->_info = (array) $this->_systemToolInfo();
		}

		return isset( $key ) ? ( isset( $this->_info[ $key ] ) ? $this->_info[ $key ] : null ) : $this->_info;
	}

	/**
	 * Indicates whether the tool is supported.
	 *
	 * @return bool
	 */
	public function systemToolSupports() {
		return true;
	}

	/**
	 * Returns the settings form for the tool step.
	 *
	 * @param string       $step
	 * @param array        $values
	 * @param array        $parents
	 * @param Context|null $context
	 * @return array
	 */
	public function systemToolSettingsForm( $step, array $values, array $parents = array(), ?Context $context = null ) {}

	/**
	 * Initializes the tool and returns an array of tasks.
	 *
	 * @param array        $settings
	 * @param array        $storage
	 * @param array        $logs
	 * @param Context|null $context
	 * @return array
	 */
	public function systemToolInit( array $settings, array &$storage, array &$logs, ?Context $context = null ) {
		return array( 'default' => 1 );
	}

	/**
	 * Called when the tool completes all tasks.
	 *
	 * @param array        $storage
	 * @param array        $logs
	 * @param mixed        $downloadFile
	 * @param Context|null $context
	 */
	public function systemToolComplete( array &$storage, array &$logs, &$downloadFile, ?Context $context = null ) {}

	/**
	 * Returns tool information array.
	 *
	 * @return array
	 */
	abstract protected function _systemToolInfo();
}
