#!/usr/bin/env php
<?php

// Potential composer autoloader paths
$paths = array(
    __DIR__ . '/../vendor/autoload.php',
    __DIR__ . '/../../../autoload.php',
);

foreach($paths as $path) {

    if (file_exists($path)) {
        include $path;
        break;
    }

}

// Everts crappy option parser.

$arguments = $argv;
array_shift($arguments);

// Re-indexing
$arguments = array_values($arguments);

$positional = array();
$named = array(
    'lt' => "%c.md",
    'namespaced-names' => false,
);


// David munging 'Everts crappy option parser'
for($i=0; $i < count($arguments); $i++) {

    if ($arguments[$i] == '--namespaced-names') {
        $named['namespaced-names'] = true;
    }
    elseif(substr($arguments[$i],0,2) === '--') {
        $named[substr($arguments[$i],2)] = $arguments[$i+1];
        $i++;
    }
    else {
        $positional[] = $arguments[$i];
    }
}


if (count($positional) < 1) {
    echo <<<EOF
PHPDocumentor Markdown Generator

Usage:

    # First generate a structure.xml file with phpdocumentor.
    # This command will generate structure.xml in the current directory.
    phpdoc  -d [project path] -t . --template="xml"

    # Next, run phpdocmd:
    {$argv[0]} structure.xml [outputdir]

Options:

    --lt [template]
        This specifies the 'template' for links we're generating. By default
        this is "%c.md".

    --namespaced-names
        Print namespaces in front of class method names

EOF;
    die();

}

$input = $positional[0];
$outputDir = isset($positional[1])?$positional[1]:'.';

$parser = new PHPDocMD\Parser(
    $input,
    $named['namespaced-names']
);

echo "Parsing structure.xml\n";

$classDefinitions = $parser->run();

$templateDir = __DIR__ . '/../templates/';

$generator = new PHPDocMD\Generator(
    $classDefinitions,
    $outputDir,
    $templateDir,
    $named['lt']
);

echo "Generating pages\n";
$generator->run();

echo "Complete\n";