<?php

namespace Snaju\Inception\Console\Command;

use Snaju\Inception\Console\InceptionCommand;
use Snaju\Inception\Console\ConsoleInput;
use Snaju\Inception\Console\ConsoleOutput;

class InitCommand extends InceptionCommand
{

    protected $name = 'init';
    
    protected $options = [
        '--disable-db-sync' => 'disables database syncing',
        '--print-hello' => 'prints a hello world message to the console'
    ];

    protected $description = 'Initializes a newly created project';
    
    public function process(ConsoleInput $input, ConsoleOutput $output)
    {
        $output->asciiBranding($this->getAppVersion());
        $output->line('Starting inception project initialization...');
        sleep(1);
        
        $output->line('Checking composer dependencies');

        if (! file_exists($this->getPath('vendor/autoload.php'))) {
            $output->tabbedLine("Running composer install for the first time");
            $exec = shell_exec('composer install --ignore-platform-reqs');
            $output->tabbedLine($exec);
        }
        
        // Load composer packages
        $output->tabbedLine('Loading composer vendor autoload');
        require $this->getPath('vendor/autoload.php');

        
        // Generate required directories, config files
        if (! file_exists($this->getPath('temp/cache/'))) {
            // TODO: determine why recursion doesn't work on windows and find solution
            mkdir($this->getPath('temp'));
            mkdir($this->getPath('temp/cache'));
        }

        if (! file_exists($this->getPath('plugins/'))) {
            mkdir($this->getPath('plugins/'));
        }


        // Copy .env-example to .env
        $output->line('Checking .env file');

        if (! file_exists($this->getPath('.env'))) {
            $output->warning('No .env file found. Copying .env-example to .env');
            $exampleEnvPath = $this->getPath('.env-example');

            if (file_exists($exampleEnvPath)) {
                copy($exampleEnvPath, $this->getPath('.env'));
                $output->tabbedLine('Successfully generated .env file');
            }
        }
            else {
                $output->tabbedLine('.env file check completed');
            }


        // Run composer update
        $output->line('Running composer update');
        $exec = shell_exec('composer update --ignore-platform-reqs');
        $output->tabbedLine($exec);
        $output->tabbedLine('Composer updated project successfully.');


        // Show completed / success message
        $output->success('Initialization completed.');
        $output->line('You\'re now ready to start hacking NASA with HTML! Good luck! :P', 'magenta');
    }
    
}