<?php
/**
* Web Application Component Toolkit
*
* @link http://www.phpwact.org/
*
* @author Wact Development Team
* @link http://www.phpwact.org/team
*
* @copyright Copyright 2006, Jeff Moore
* @license http://opensource.org/licenses/mit-license.php MIT
*/

/**
* Command that dispatches to other commands
*/
class Wact_Tool_Cli_Dispatcher extends Wact_Tool_Cli_Command {

    /**
    */
    protected $commandLoader;

    /**
    * Class constructor
    */
    public function __construct() {
        parent::__construct();

        $this->commandLoader = new Wact_Plugin_Loader('.cmd.php');
        $this->commandLoader->addPath('Wact/Tool/Cli/command', 'Wact_Cli_Command');

        $this->options->addOption(new Wact_Tool_Cli_Option(
            'project',
            "Set the current project directory.",
            'project=',
            'p:'
            ));

    }

    /**
    * Get a list of all known commands
    */
    public function getCommands() {
        $this->commandLoader->scanAll();
        return $this->commandLoader->getKnown();
    }

    /**
    * Pick a command to run based on a command name.  If the command name is not
    * found, the help command is chosen.
    */
    public function findCommand($command) {
        $pluginclass = $this->commandLoader->load($command);
        if ($pluginclass) {
            return new $pluginclass();
        } else {
            return FALSE;
        }
    }

    /**
    * Run this command
    */
    public function run($argv = array(), $dispatcher = NULL, $project = NULL) {

        array_shift($argv);

        $projectDir = realpath('.');

        $options = $this->options->parse($argv);

        foreach ($options[0] as $option) {
            $param = !empty($option[1]) ? $option[1] : true;
            switch ($option[0]) {
                case 'project':
                    $projectDir = realpath($option[1]);
                    break;
                default:
                    throw new Exception("Unsupported option '{$option[0]}' detected.\n");
                    break;
            }
        }
        
        $project = Wact_Tool_Project::Load($projectDir);

        $args = $options[1];
        $command = array_shift($args);

        if ($cmd = $this->findCommand($command)) {
            $cmd->run($args, $this, $project);
        } else if ($cmd = $this->findCommand('help')) {
            $cmd->run($args, $this, $project);
        } else {
            echo "Unknown command '{$command}'.\n";
        }
    }
}

?>