#!/usr/bin/env php
<?php namespace Clean\PhpDocMd;

use ReflectionClass;

require 'vendor/autoload.php';
$config = require '.phpdoc-md';

function getDestinationDirectory(ReflectionClass $reflection, $rootNamespace, $rootDir)
{
    return namespaceToPath(
        rtrim(
            sprintf(
                '%s/%s',
                $rootDir,
                removeRootNamespace($reflection->getNamespaceName(), $rootNamespace)
            ),
            '/'
        )
    );
}

function namespaceToPath($namespace)
{
    return str_replace(
        '\\',
        DIRECTORY_SEPARATOR,
        $namespace
    );
}

function removeRootNamespace($namespace, $root)
{
    $re = preg_replace(
        sprintf("/^%s/", addslashes($root)),
        '',
        $namespace
    );
    return ltrim($re, '\\');
}

function error($message, $exception = null) {
    echo sprintf("ERROR: '%s'", trim($message));
    exit(1);
}

switch ($config->format) {
    default:
        $readme = new Markdown\GitHub\Readme($config->rootNamespace);
}

foreach ($config->classes as $class) {
    try {
        $reflection = new ReflectionClass($class);
    } catch(\ReflectionException $e) {
        error('Config error: ' . $e->getMessage(), $e);
    }
    $destDir = getDestinationDirectory($reflection, $config->rootNamespace, $config->destDirectory);
    $destFile = sprintf('%s.md', $reflection->getShortName());
    switch ($config->format) {
        case 'stash':
            $markDown = new Markdown\Stash\ClassInfo($reflection);
            break;
        case 'github':
            $markDown = new Markdown\GitHub\ClassInfo($reflection);
            break;
        default:
            throw new \RuntimeException('Not supported markdown format given: ' . $config->format);

    }

    file_exists($destDir) ?: mkdir($destDir, 0777, true);
    file_put_contents($destDir . DIRECTORY_SEPARATOR . $destFile, $markDown);
    $readme->addLink(
        removeRootNamespace($reflection->getName(), $config->rootNamespace),
        namespaceToPath(
            removeRootNamespace(
                $reflection->getName(),
                $config->rootNamespace
            )
        ) . '.md'
    );
}

file_put_contents($config->destDirectory . '/README.md', $readme);
