#!/usr/bin/env php
<?php
/* (c) Anton Medvedev <anton@medv.io>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Deployer;

use Deployer\Support\Changelog\Item;
use Deployer\Support\Changelog\Parser;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Style\SymfonyStyle;

require __DIR__ . '/../vendor/autoload.php';

chdir(realpath(__DIR__ . '/..'));
define('CHANGELOG', 'CHANGELOG.md');

$input = new ArgvInput();
$output = new ConsoleOutput();
$app = new Application('Changelog', '1.0.0');
$io = new SymfonyStyle($input, $output);

$app->setDefaultCommand('update');
$app->register('update')->setCode(function () use ($io) {
    $parser = new Parser(file_get_contents(CHANGELOG), false);
    $changelog = $parser->parse();

    $type = $io->choice('What kind of change do you want to report?', ['Added', 'Fixed', 'Changed', 'Removed']);

    $item = new Item();

    $message = $io->ask('What is ' . strtolower($type) . '?');
    $message = ucfirst($message);
    $message = trim(rtrim($message, '.'));

    $item->setMessage($message);

    do {
        $noop = 'or leave blank';
        $url = $io->ask('Closed issues/pulls url', $noop);
        if ($url === $noop) {
            break;
        }

        if (preg_match('#^https\://github\.com/deployphp/deployer/(issues|pull)/(\d+)$#', $url, $m)) {
            $ref = (int)$m[2];
            $item->addReference($ref);
            $changelog->addReferences($ref, $url);
        } else {
            $io->warning('Url should be link to GitHub issue or pull page of deployphp/deployer repo.');
        }
    } while (true);

    $changelog->findMaster()->{"add$type"}($item);

    file_put_contents(CHANGELOG, (string)$changelog);

    $io->success(CHANGELOG . ' updated');
});

$app->register('fix')->setCode(function () use ($io) {
    $parser = new Parser(file_get_contents(CHANGELOG), false);
    $changelog = $parser->parse();
    file_put_contents(CHANGELOG, (string)$changelog);
});

$app->register('release')->setCode(function () use ($io) {
    $parser = new Parser(file_get_contents(CHANGELOG), false);
    $changelog = $parser->parse();

    $latest = $changelog->findLatest();

    do {
        $v = $io->ask("What version to release? (latest {$latest->getVersion()})");
        if (!preg_match('/^\d+\.\d+\.\d+(-[\w\.]+)?$/', $v)) {
            $io->warning('Version number must follow semantic versioning.');
            continue;
        }
        break;
    } while (true);

    $changelog->findMaster()->setVersion('v' . $v);

    file_put_contents(CHANGELOG, (string)$changelog);
    $io->success(CHANGELOG . " updated to v$v");
});

$app->run($input, $output);
