/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2025 SteamWar.de-Serverteam
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Affero General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   GNU Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package de.steamwar.command;

import de.steamwar.core.Core;
import de.steamwar.message.Message;
import lombok.Setter;
import net.md_5.bungee.api.chat.ClickEvent;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import java.util.logging.Level;

public class SWCommand extends AbstractSWCommand<CommandSender> {

    static {
        TypeUtils.init();
    }

    private Command command;

    @Setter
    protected Message message = null;
    private List<String> defaultHelpMessages = new ArrayList<>();

    protected SWCommand(String command) {
        super(CommandSender.class, command);
    }

    protected SWCommand(String command, String... aliases) {
        super(CommandSender.class, command, aliases);
    }

    @Override
    protected void createAndSafeCommand(String command, String[] aliases) {
        this.command = new Command(command, "", "/" + command, Arrays.asList(aliases)) {
            @Override
            public boolean execute(CommandSender sender, String alias, String[] args) {
                SWCommand.this.execute(sender, alias, args);
                return false;
            }

            @Override
            public List<String> tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException {
                return SWCommand.this.tabComplete(sender, alias, args);
            }
        };
    }

    @Override
    public void unregister() {
        CommandRegistering.unregister(this.command);
    }

    @Override
    public void register() {
        CommandRegistering.register(this.command);
    }

    @Override
    protected void commandSystemError(CommandSender sender, CommandFrameworkException e) {
        Bukkit.getLogger().log(Level.SEVERE, e.getMessage(), e);
        Core.MESSAGE.sendPrefixless("COMMAND_SYSTEM_ERROR", sender);
    }

    @Override
    protected void commandSystemWarning(Supplier<String> message) {
        Bukkit.getLogger().log(Level.WARNING, message);
    }

    public void addDefaultHelpMessage(String message) {
        defaultHelpMessages.add(message);
    }

    @Override
    protected void sendMessage(CommandSender sender, String message, Object[] args) {
        this.message.send(message, sender, args);
    }

    @Override
    protected void initialisePartOf(AbstractSWCommand parent) {
        if (parent instanceof SWCommand) {
            this.message = ((SWCommand) parent).message;
        }
    }

    @Register(help = true)
    public void internalHelp(Player p, String... args) {
        if (message == null) {
            return;
        }
        try {
            message.sendPrefixless("COMMAND_HELP_HEAD", p, command.getName().substring(0, 1).toUpperCase() + command.getName().substring(1));
            defaultHelpMessages.forEach(s -> message.sendPrefixless(s, p));
        } catch (Exception e) {
            Bukkit.getLogger().log(Level.WARNING, "Failed to send help message", e);
            return;
        }
        AtomicInteger atomicInteger = new AtomicInteger();
        if (args.length != 0) {
            commandList.forEach(subCommand -> {
                List<String> tabCompletes = subCommand.tabComplete(p, args);
                if (tabCompletes == null || tabCompletes.isEmpty()) {
                    atomicInteger.incrementAndGet();
                    return;
                }
                boolean hasTabCompletes = tabCompletes.stream()
                        .anyMatch(s -> s.toLowerCase().startsWith(args[args.length - 1].toLowerCase()));
                if (hasTabCompletes) {
                    send(p, subCommand);
                } else {
                    atomicInteger.incrementAndGet();
                }
            });
        }
        if (args.length == 0 || atomicInteger.get() == commandList.size()) {
            commandList.forEach(subCommand -> {
                if (subCommand.validator == null || subCommand.validator.validate(p, p, (s, args1) -> {
                })) {
                    send(p, subCommand);
                }
            });
        }
    }

    private void send(Player p, SubCommand<CommandSender> subCommand) {
        try {
            for (String s : subCommand.description) {
                String hover = "§8/§e" + command.getName() + " " + String.join(" ", subCommand.subCommand);
                String suggest = "/" + command.getName() + " " + String.join(" ", subCommand.subCommand);
                message.sendPrefixless(s, p, hover, new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, suggest));
            }
        } catch (Exception e) {
            Bukkit.getLogger().log(Level.WARNING, "Failed to send description of registered method '" + subCommand.method + "' with description '" + subCommand.description + "'", e);
        }
    }
}
