package tech.nevets.tvpn.cli

import tech.nevets.tvpn.cli.commands.*
import tech.nevets.tvpn.Logger

class CommandBrigadier {
    private val logger: Logger = Logger(CommandBrigadier::class.java)
    private val registeredCmds: List<Command> = ArrayList()
    private val helpCmd: HelpCmd = HelpCmd(this)

    init {
        registerCmd(helpCmd)
        registerCmd(InstallTunnelServiceCmd())
        registerCmd(UninstallTunnelServiceCmd())
        registerCmd(VersionCmd())
    }

    private fun registerCmd(cmd: Command) {
        for (c in registeredCmds) {
            if (c.getName() == cmd.getName()) {
                logger.warn("Command with name " + cmd.getName() + " already registered, skipping.")
                return
            }
        }
        registeredCmds.addLast(cmd)
    }

    fun execute(args: Array<String>) {
        for (c in registeredCmds) {
            if (c.getName() == args[0]) {
                c.execute(args)
                return
            }
        }
        helpCmd.execute(arrayOf(""))
    }

    fun getCommands(): List<Command> {
        return registeredCmds
    }
}