import CommanderCommand from './CommanderCommand.js';
import ora              from 'ora';
import Config           from '../config/Config.js';
import TextStyle        from '../types/TextStyle.js';
import os               from 'os';
import { spawn }        from 'child_process';


class UpgradeCommand extends CommanderCommand {
    protected commandName: string = 'upgrade';

    protected defineCommand() {
        this.command.description('upgrade the DojoCLI.')
            .option('--pre-alpha', 'upgrade to the latest pre-alpha (dev) version. Attention it\'s an unstable version without support.')
            .option('-o, --instructions', 'only display upgrade instructions.')
            .action(this.commandAction.bind(this));
    }

    private displayInstructions(upgradeCommand: string, preAlpha: boolean) {
        upgradeCommand = TextStyle.CODE(` ${ upgradeCommand } `);
        
        console.log(TextStyle.BLOCK(`You can upgrade DojoCLI on ${ os.platform() === 'darwin' ? 'macOS' : 'Linux' }:`));
        ora().start().info(`By executing this command: ${ upgradeCommand }`);
        console.log('or');
        ora().start().info(`By downloading the release from: ${ preAlpha ? Config.gitlab.cliPreAlphaReleasePage : Config.gitlab.cliReleasePage }`);
    }

    private upgrade(upgradeCommand: string) {
        const upgradeSpinner = ora().start('DojoCLI upgrade is in progress. Please wait...');

        const upgradeProcess = spawn(upgradeCommand, {
            shell: true
        });

        upgradeProcess.on('exit', code => {
            code === null || code !== 0 ? upgradeSpinner.fail('DojoCLI upgrade failed... Please try again manually.') : upgradeSpinner.succeed('DojoCLI upgrade is successful.');
        });
    }

    protected async commandAction(options: { preAlpha: boolean, instructions: boolean }): Promise<void> {
        if ( os.platform() === 'win32' ) {
            if ( !options.instructions ) {
                ora().start().warn('Automatic upgrade is not supported on Windows. \n');
            }

            console.log(TextStyle.BLOCK('You can upgrade DojoCLI on Windows:'));
            ora().start().info(`By downloading the release from: ${ options.preAlpha ? Config.gitlab.cliPreAlphaReleasePage : Config.gitlab.cliReleasePage }`);

            return;
        }

        const upgradeCommand = `curl -L "https://dojo.isc-hesge.ch/installer.sh" | sh /dev/stdin${ options.preAlpha ? ' installer=pre-alpha' : '' }`;

        if ( options.instructions ) {
            this.displayInstructions(upgradeCommand, options.preAlpha);
        } else {
            this.upgrade(upgradeCommand);
        }
    }
}


export default new UpgradeCommand();