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

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

use Symfony\Component\Console\Application;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Oncli\Command;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\Console\Event\ConsoleTerminateEvent;

$dispatcher = new EventDispatcher();
$application = new Application('Oncli', '1.6.5');

$application->add(new Command\DrushCommand());
$application->add(new Command\ModuleEnableCommand());
$application->add(new Command\ModuleDisableCommand());
$application->add(new Command\Bash());
$application->add(new Command\ConfigExport());
$application->add(new Command\Start());
$application->add(new Command\Stop());
$application->add(new Command\Gulp());
$application->add(new Command\Deploy());
$application->setDispatcher($dispatcher);

// Before any command check for updates and notify the user.
$dispatcher->addListener(ConsoleEvents::COMMAND, function (ConsoleCommandEvent $event) {
  check_version($event);
});

$dispatcher->addListener(ConsoleEvents::TERMINATE, function (ConsoleTerminateEvent $event) {
  check_version($event);
});

$application->run();

function check_version($event) {
  $json = file_get_contents('https://repo.onlynet.gr/oncli.version');

  if ($json) {
    $output = $event->getOutput();
    $command = $event->getCommand();
    $application = $command->getApplication();
    $app_version = $application->getVersion();
    $version = json_decode($json);
    $version = $version->version;

    if (version_compare($version, $app_version, '>')) {
      $output->writeln("A new version is available. Please update oncli to $version by using the command below:");
      $output->writeln("<info>composer global update onlynet/oncli</info>");
    }
  }
}
