import { Command } from "./command";

const { program } = require('commander');

export class CreateCommand implements Command {
    
    protected roundCount = 0;
    protected mainChannel: any;

    protected getMessage(params: { master: string, system?: string, setting?: string, note?: string, min?: number, max: number }, number: number): string {
        let message = `Runde ${number}\n`;
        message += `Meister: ${params.master}\n`;
        if (params.system) {
            message += `System: ${params.system}\n`;
        }

        if (params.setting) {
            message += `Setting: ${params.setting}\n`;
        }
        if (params.max) {
            message += `Spieleranzahl: max. ${params.max} Spieler `;
            if (params.min) {
                message += `min ${params.min} Spieler`
            }
            message += '\n';
        }
        if (params.note) {
            message += `${params.note}\n`;
        }
        return message;
    }

    constructor(mainChannel: any) {
        this.mainChannel = mainChannel;

        program.exitOverride();
        program
            .option('-ma, --master <name>', 'Name of Master')
            .option('--system <description>', 'Name or Descripion of System (Optional)')
            .option('--setting <description>', 'Name or Descripion of Setting (Optional)')
            .option('--note <description>', 'Some extra Notes (Optional)')
            .option('--min <count>', ' Minum Player Count (Optional)')
            .option('--max <count>', 'Maximum Player Count')
    }

    public call(msg: any, options?: string[]): any {
        if (options) {
            options = ['', '', ...options];
            program.on('option:*', function (operands: string[]) {
                msg.reply(`error: unknown option '${operands[0]}'`);
            });

            try {
                program.parse(options);
            } catch (err) {
                msg.reply(err.message);
                return;
            }
            if (!program.master) {
                msg.reply('error: missing option master');
                return;
            }

            if (!program.max) {
                msg.reply('error: missing option max');
                return;
            }

        }
        this.start(msg);
    }

    protected start(msg: any): any {
        this.roundCount++;
        const message = this.getMessage(
            {
                master: program.master ? program.master : null,
                max: program.max ? program.max : null,
                min: program.min ? program.min : null,
                note: program.note ? program.note : null,
                setting: program.setting ? program.setting : null,
                system: program.system ? program.system : null,
            },
            this.roundCount
        );
        if (this.mainChannel.lastMessage) {
            this.mainChannel.send('=============');    
        }
        this.mainChannel.send(message);
    }


}