package pw.hamzantal.vagueenchants.commands

import org.bukkit.Bukkit
import org.bukkit.command.Command
import org.bukkit.command.CommandSender
import org.bukkit.command.TabCompleter
import org.bukkit.enchantments.Enchantment
import pw.hamzantal.vagueenchants.subCommands

class VECompleter : TabCompleter {
    override fun onTabComplete(
        sender: CommandSender,
        command: Command,
        alias: String,
        args: Array<out String>
    ): MutableList<String> {
        if (command.name != "ve") return mutableListOf()

        if (args.size == 1) return subCommands.map { it.firstArg } has args.first()

        val sbcmd = subCommands.firstOrNull { it.firstArg == args.first() } ?: return mutableListOf()
        if ((sbcmd.usage.split(" ").size - 1) < args.size) return mutableListOf()
        val type = sbcmd.usage.split(" ")[args.size]

        if (type.contains("player")) return Bukkit.getOnlinePlayers().map { it.name } has args.last()
        if (type.contains("command")) return subCommands.map { it.firstArg } has args.last()
        if (type.contains("enchantment")) return (Enchantment.values().filter { it.id in 400..500 }.map { it.name.toLowerCase() }
            .toMutableList().also { it.addAll(listOf("fortune", "efficiency")) } has args.last())
        if (type.contains("level")) return mutableListOf("1")

        return mutableListOf()
    }
}

infix fun Iterable<String>.has(me: String): MutableList<String> =
    listOf(
        sorted().filter { it.startsWith(me, ignoreCase = true) },
        sorted().filter { it.contains(me, ignoreCase = true) })
        .flatten()
        .distinct()
        .toMutableList()