package me.StevenLawson.TotalFreedomMod.commands;

import me.StevenLawson.TotalFreedomMod.util.Utilities;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import java.nio.file.Files;
import java.nio.file.Paths;

@CommandPermissions(level = AdminLevel.SENIOR, source = SourceType.BOTH)
public class Command_resetplayer extends FreedomCommand {
    @Override
    public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) {
        if(args.length < 1) {
            return false;
        }

        OfflinePlayer target = null;
        String searchString = args[0];

        for (OfflinePlayer offlinePlayer : Bukkit.getOfflinePlayers()) {
            if(offlinePlayer.getName().equalsIgnoreCase(searchString)) {
                target = offlinePlayer;
                break;
            }  else if (offlinePlayer.getName().startsWith(searchString.toLowerCase())) {
                target = offlinePlayer;
                break;
            }
        }

        if(target == null) {
            playerMsg(sender, FreedomCommand.PLAYER_NOT_FOUND);
            return true;
        }

        if(target.isOnline()) {
            target.getPlayer().kickPlayer(ChatColor.RED + "YOU ARE BEING RESET.");
        }

        Utilities.adminAction(sender.getName(), String.format("Resetting %s's player data", target.getName()), true);
        playerMsg(sender, String.format("Resetting %s's player data (excluding TFM)...", target.getName()));
        try {
            String uuid = target.getUniqueId().toString();
            Files.deleteIfExists(Paths.get(".", "world", "playerdata", uuid + ".dat"));
            Files.deleteIfExists(Paths.get(".", "plugins", "Essentials", "userdata", uuid + ".yml"));
            playerMsg(sender, "Done.");
        } catch (Exception e) {
            e.printStackTrace();
            playerMsg(sender, "Oops");
        }

        return true;
    }
}
