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

include_once getcwd() . DIRECTORY_SEPARATOR . 'vendor/autoload.php';

if (count($argv) == 1) {
    die("Directory path is required\n");
}

if (count($argv) == 2) {
    die("Destination directory path is required\n");
}

$resource = $argv[1];
$destination = $argv[2];
$options = [
    'language' => 'en',
    'format' => 'html'
];

foreach ($argv as $arg) {
    if ($arg[0] == '-') {
        $start = 1;
        if ($arg[1] == '-') {
            $start = 2;
        }

        $arg = substr($arg, $start, strlen($arg) - 1);
        $arg = explode('=', $arg);

        if (isset($arg[1]) && $arg[1] != null) {
            $options[$arg[0]] = $arg[1];
        }
    }
}

if (!file_exists(__DIR__ . '/../translations/' . $options['language'] . '.json')) {
    die("Language file does not exists!\n");
}
$language = json_decode(
    file_get_contents(__DIR__ . '/../translations/' . $options['language'] . '.json'),
    true
);

if (!in_array($options['format'], ['html', 'json'])) {
    die("Available formats are 'html' and 'json'\n");
}

$docGenerator = new \IcyMat\ApiDoc\ApiDoc();
$docData = $docGenerator->generarteDoc(getcwd() . DIRECTORY_SEPARATOR . $resource);

$docGenerator = new \IcyMat\ApiDoc\Docs\DocumentationGenerator();
$docData = $docGenerator->createDocData($docData);

if (!file_exists(getcwd() . DIRECTORY_SEPARATOR . $destination)) {
    mkdir(getcwd() . DIRECTORY_SEPARATOR . $destination);
}

$loader = new \Twig\Loader\FilesystemLoader(__DIR__ . '/../views');
$twig = new \Twig\Environment($loader);
$twig->addExtension(new \IcyMat\ApiDoc\Twig\JsonFormatterExtension());

$docPath = getcwd() . DIRECTORY_SEPARATOR . $destination . '/documentation.' . $options['format'];

if ($options['format'] == 'json') {
    file_put_contents(
        $docPath,
        json_encode($docData)
    );
} else {
    $f = fopen($docPath, 'w+');
    fputs($f, $twig->render('index.html.twig', ['documentation' => $docData, 'trans' => $language]));
    fclose($f);
}

echo "Done\n";
