package org.openautonomousconnection.webserver;

import dev.unlegitdqrk.unlegitlibrary.command.CommandExecutor;
import dev.unlegitdqrk.unlegitlibrary.command.CommandManager;
import dev.unlegitdqrk.unlegitlibrary.command.CommandPermission;
import dev.unlegitdqrk.unlegitlibrary.event.EventManager;
import dev.unlegitdqrk.unlegitlibrary.file.ConfigurationManager;
import dev.unlegitdqrk.unlegitlibrary.network.system.packets.PacketHandler;
import lombok.Getter;
import org.openautonomousconnection.protocol.ProtocolBridge;
import org.openautonomousconnection.protocol.ProtocolValues;
import org.openautonomousconnection.protocol.versions.ProtocolVersion;
import org.openautonomousconnection.webserver.commands.StopCommand;

import java.io.File;
import java.util.Scanner;

public class Main {
    public static final CommandPermission PERMISSION_ALL = new CommandPermission("all", 1);
    private static final CommandExecutor commandExecutor = new CommandExecutor("WebServer", PERMISSION_ALL) {};

    @Getter
    private static CommandManager commandManager;

    @Getter
    private static ProtocolBridge protocolBridge;

    @Getter
    private static ProtocolValues values;

    public static void main(String[] args) throws Exception {
        values = new ProtocolValues();
        values.packetHandler = new PacketHandler();
        values.eventManager = new EventManager();

        ConfigurationManager config = new ConfigurationManager(new File("config.properties"));

        if (!config.isSet("port.udp")) {
            config.set("port.udp", 1027);
            config.saveProperties();
        }

        if (!config.isSet("port.tcp")) {
            config.set("port.tcp", 1028);
            config.saveProperties();
        }

        if (!config.isSet("sessionexpiremin")) {
            config.set("sessionexpiremin", 1000);
            config.saveProperties();
        }

        if (!config.isSet("maxuploadmb")) {
            config.set("maxuploadmb", 1024);
            config.saveProperties();
        }

        int tcpPort = config.getInt("port.tcp");
        int udpPort = config.getInt("port.udp");

        int sessionExpire = config.getInt("sessionexpiremin");
        int maxUpload = config.getInt("maxuploadmb");

        protocolBridge = new ProtocolBridge(new WebServer(
                new File("auth.ini"), new File("rules.ini"),
                tcpPort, udpPort,
                sessionExpire, maxUpload),
                values, ProtocolVersion.PV_1_0_0_BETA, new File("logs"));

        protocolBridge.getProtocolServer().getNetwork().start();

        commandManager = new CommandManager(values.eventManager);
        commandManager.registerCommand(StopCommand.class);

        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.print(commandExecutor.getName() + "> ");
            String line = scanner.nextLine();
            commandManager.execute(commandExecutor, line);
        }

    }
}