package net.knarcraft.blacksmith.command;

import net.knarcraft.blacksmith.config.NPCSetting;
import net.knarcraft.blacksmith.util.TabCompleteValuesHelper;
import net.knarcraft.blacksmith.util.TabCompletionHelper;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

/**
 * The tab completer for the blacksmith editing command
 */
public class BlackSmithEditTabCompleter implements TabCompleter {

    @Nullable
    @Override
    public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label,
                                      @NotNull String[] args) {
        List<String> npcSettings = new ArrayList<>();
        for (NPCSetting setting : NPCSetting.values()) {
            npcSettings.add(setting.getCommandName());
        }

        if (args.length == 1) {
            if (!sender.hasPermission("blacksmith.edit")) {
                return new ArrayList<>();
            }
            return TabCompletionHelper.filterMatchingContains(npcSettings, args[0]);
        } else {
            if (npcSettings.contains(args[0]) && args.length <= 2) {
                return tabCompleteCommandValues(args[0], args[1]);
            } else {
                return new ArrayList<>();
            }
        }
    }

    /**
     * Tab completes the values available for the given command
     *
     * @param commandName  <p>The name of the used command</p>
     * @param commandValue <p>The command value used to filter tab-completions</p>
     * @return <p>Some valid options for the command's argument</p>
     */
    private List<String> tabCompleteCommandValues(String commandName, String commandValue) {
        for (NPCSetting npcSetting : NPCSetting.values()) {
            if (npcSetting.getCommandName().equalsIgnoreCase(commandName)) {
                return TabCompletionHelper.filterMatchingContains(TabCompleteValuesHelper.getTabCompletions(
                        npcSetting.getValueType()), commandValue);
            }
        }
        return null;
    }

}
