<?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
*/

/**
* A list of command line options.
*/
class Wact_Tool_Cli_Option_List {
    protected $options = array();
    
    /**
    * Add an option to this list
    */
    function addOption($option) {
        $this->options[] = $option;
    }
    
    /**
    * Get a short option string in Console_Getopt format
    */
    protected function getShortOptions() {
        $short = '';
        foreach ($this->options as $option) {
            if (isset($option->short)) {
                $short .= $option->short;
            }                
        }
        return $short;
    }
    
    /**
    * Get a long option array in Console_Getopt format.
    */
    protected function getLongOptions() {
        $long = array();
        foreach ($this->options as $option) {
            if (isset($option->long)) {
                $long[] = $option->long;
            }
        }
        return $long;
    }
    
    /**
    */
    protected function getOptionMap() {
        $map = array();
        foreach ($this->options as $option) {
            if (isset($option->long)) {
                $map['--' . trim($option->long, '=')] = $option->name;
            }
            if (isset($option->short)) {
                $map[trim($option->short, ':')] = $option->name;
            }
        }
        return $map;
    }

    /**
    * Parse a list of parameters into an array of options and leftover arguments
    */
    public function parse($argv) {
        $options = Console_Getopt::getopt2($argv, 
            $this->getShortOptions(), 
            $this->getLongOptions());
        if (PEAR::isError($options)) {
            echo $options->getMessage() . "\n";
            exit;
        }

        $map = $this->getOptionMap();
    
        foreach($options[0] as $key => $pair) {
            $options[0][$key][0] = $map[$options[0][$key][0]];
        }
        
        return $options;
    }
    
    /**
    * Print the list of available options
    */
    public function printOptions() {

        if (count($this->options) == 0) {
            echo "This command has no options.\n";
        } else {
            $size = 5;
            foreach ($this->options as $option) {
                $size = max($size, strlen($option->long));
            }

            echo "Options:\n";
            foreach($this->options as $option) {
                $option->printDescription($size, 79);
            }
        }
    }
}

?>