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

use Garden\Cli\Cli;
use Aivec\WordPress\CodeceptDocker\Config;
use Aivec\WordPress\CodeceptDocker\Logger;
use Aivec\WordPress\CodeceptDocker\CLI\Client;
use Aivec\WordPress\CodeceptDocker\CLI\Commands;

require_once 'vendor/autoload.php';

$logger = new Logger();

// Define a cli with commands.
$cli = Cli::create()
    ->command('create-config')
    ->description('Create codecept-docker.json config file in project directory.')
    ->opt('namespace:n', 'Prefix for Docker containers', false, 'string')
    ->opt('type:t', 'Project type. Must be one of "plugin", "theme", or "library"', true, 'string')
    ->command('init')
    ->description('Create Docker containers and Codeception scaffolding')
    ->command('up')
    ->description('Create Docker containers. If you also want Codeception scaffolding, use "init" instead.')
    ->command('start')
    ->description('Start stopped containers')
    ->command('stop')
    ->description('Stop running containers')
    ->command('down')
    ->description('Stops and removes containers. NOTE: you will have to call "up" again if you do this')
    ->command('update')
    ->description('Updates wordpress and wp-cli Docker images to latest')
    ->command('codecept')
    ->description('Calls and passes args to codecept script from within Docker container')
    ->command('wp-cli')
    ->description('Runs and passes command/arguments to wp-cli container for Docker installs');

// Parse and return cli args.
$args = $cli->parse($argv, true);

if (!in_array($argv[1], ['create-config', 'update'], true)) {
    if (!file_exists(Client::getAbsPath() . '/codecept-docker.json')) {
        $logger->error('codecept-docker.json does not exist in project directory. Create one with "aivec-codecept create-config --type=<type>"');
        exit(1);
    }
}

switch ($argv[1]) {
    case 'create-config':
        Commands\CreateConfig::createConfig((string)$args->getOpt('type'), (string)$args->getOpt('namespace'));
        break;
    case 'init':
        (new Commands\Init(new Commands\CreateEnvironments((new Client(new Config())))))->init();
        break;
    case 'up':
        (new Commands\CreateEnvironments((new Client(new Config()))))->createEnvironments();
        break;
    case 'start':
        (new Commands\Start((new Client(new Config()))))->start();
        break;
    case 'stop':
        (new Commands\Stop((new Client(new Config()))))->stop();
        break;
    case 'down':
        (new Commands\Down((new Client(new Config()))))->down();
        break;
    case 'update':
        Commands\Update::updateImages();
        break;
    case 'codecept':
        (new Client(new Config()))->codecept(isset($argv[2]) ? join(' ', array_slice($argv, 2)) : '');
        break;
    case 'wp-cli':
        (new Client(new Config()))->wpcli($argv);
        break;
}
