package dk.itu.real.ooe;

import dk.itu.real.ooe.services.MinecraftService;
import com.google.inject.Inject;
import io.grpc.ServerBuilder;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.LinearComponents;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.Style;
import net.kyori.adventure.text.format.TextDecoration;
import org.apache.logging.log4j.Logger;
import org.spongepowered.api.Server;
import org.spongepowered.api.command.Command;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.parameter.Parameter;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.lifecycle.ConstructPluginEvent;
import org.spongepowered.api.event.lifecycle.RegisterCommandEvent;
import org.spongepowered.api.event.lifecycle.StartingEngineEvent;
import org.spongepowered.plugin.PluginContainer;
import org.spongepowered.plugin.builtin.jvm.Plugin;

import java.io.IOException;
@Plugin("minecraft-rpc")
public class MinecraftRPC {

    private final PluginContainer plugin;
    private final Logger logger;

    private MinecraftService minecraftService;

    @Inject
    MinecraftRPC(final PluginContainer container, final Logger logger) {
        this.plugin = container;
        this.logger = logger;
        this.logger.info("Creating MinecraftRPC class");
    }

    @Listener
    public void onConstructPlugin(final ConstructPluginEvent event) {
        // Perform any one-time setup
        this.logger.info("Constructing minecraft_rpc");
    }
    /**
     * Called on server startup.
     *
     * @param event The server startup event
     */
    @Listener
    public void onServerStarting(final StartingEngineEvent<Server> event) throws IOException, IllegalAccessException {
        logger.info("Starting the grpc server");
        this.minecraftService = new MinecraftService(plugin);
        ServerBuilder.forPort(5001).addService(this.minecraftService).build().start();
        logger.info("Listening on 5001");
    }

    @Listener
    public void onRegisterCommands(final RegisterCommandEvent<Command.Parameterized> event) {
        // Register a simple command
        // When possible, all commands should be registered within a command register event
        final Parameter.Value<String> messageTextParam = Parameter.remainingJoinedStrings().key("message_text").build();
        event.register(this.plugin, Command.builder()
            .addParameter(messageTextParam)
            .permission("minecraft-rpc.command.message")
            .executor(ctx -> {
                final String message = ctx.requireOne(messageTextParam);
                minecraftService.sendResponse(message);
                return CommandResult.success();
            })
            .build(), "message", "response"
        );
    }

}

