package de.hessj.dailyquests;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;
import java.util.AbstractMap.SimpleEntry;
import java.util.Map.Entry;
import com.destroystokyo.paper.profile.PlayerProfile;
import com.destroystokyo.paper.profile.ProfileProperty;

import de.hessj.helper.Helper.Type;

import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.scoreboard.DisplaySlot;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Score;
import org.bukkit.scoreboard.Scoreboard;
import net.kyori.adventure.text.Component;
import net.md_5.bungee.api.ChatColor;

public class DailyQuestsCommands implements CommandExecutor {

    public static HashMap<String, Entry<Scoreboard, Boolean>> boards = new HashMap<String, Entry<Scoreboard, Boolean>>();
    public static NamespacedKey nsksurpriseBox;
    public static ItemStack surpriseBox;
    public static de.hessj.helper.Helper helper = new de.hessj.helper.Helper();

    public static void updateSB(Player p) {
        if (!(boards.containsKey(p.getName()))) {

            Scoreboard board = Bukkit.getServer().getScoreboardManager().getNewScoreboard();
            boards.put(p.getName(), new SimpleEntry<Scoreboard, Boolean>(board, false));
        }
        Entry<Scoreboard, Boolean> actionMapEntry = boards.get(p.getName());
        Scoreboard board = actionMapEntry.getKey();

        if (board.getObjective(DisplaySlot.SIDEBAR) != null) {
            board.getObjective(DisplaySlot.SIDEBAR).unregister();
        }
        Objective o = board.registerNewObjective("test", "dummy", Component.text("Quest:"));


        o.setDisplaySlot(DisplaySlot.SIDEBAR);
        Score score;
        for (Object obj : App.main.getConfig().getConfigurationSection("players." + p.getUniqueId() + ".currentQuests")
                .getKeys(false).toArray()) {

            if (!obj.toString().equals("null")) {
                String desc = "";
                if (!App.main.getConfig().get("quests." + obj.toString() + ".tool").equals("none")) {
                    desc = (App.main.getConfig().get("quests." + obj.toString() + ".description")).toString()
                            .replace("[x]",
                                    App.main.getConfig()
                                            .get("players." + p.getUniqueId() + ".currentQuests." + obj.toString()
                                                    + ".countneeded")
                                            .toString()/*
                                                        * App.main.getConfig().get("quests." + obj.toString() +
                                                        * ".count").toString()
                                                        */)
                            .replace("[b]", App.main.getConfig().get("quests." + obj.toString() + ".target").toString())
                            .replace("[t]", App.main.getConfig().get("quests." + obj.toString() + ".tool").toString()
                                    .replace("Material.", ""));

                } else {
                    desc = App.main.getConfig().get("quests." + obj.toString() + ".description").toString()
                            .replace("[x]",
                                    App.main.getConfig()
                                            .get("players." + p.getUniqueId() + ".currentQuests." + obj.toString()
                                                    + ".countneeded")
                                            .toString())
                            .replace("[b]",
                                    App.main.getConfig().get("quests." + obj.toString() + ".target").toString());

                }
                desc = desc.replace("Material.", "");
                if (desc.length() >= 39) {
                    desc = desc.substring(0, 39);
                }
                if (App.main.getConfig()
                        .get("players." + p.getUniqueId() + ".currentQuests." + obj.toString() + ".state")
                        .equals("finished")) {
                    board.resetScores(desc);
                    score = o.getScore(ChatColor.STRIKETHROUGH + "" + desc);
                } else {
                    score = o.getScore(desc);
                }
                score.setScore(App.main.getConfig()
                        .getInt("players." + p.getUniqueId() + ".currentQuests." + obj.toString() + ".currentcount"));
                checkForCompletion(p);
            }
        }
        if (actionMapEntry.getValue()) {
            boards.put(p.getName(), new SimpleEntry<Scoreboard, Boolean>(board, true));
        } else {
            boards.put(p.getName(), new SimpleEntry<Scoreboard, Boolean>(board, false));
        }
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (sender instanceof Player) {
            updateSB((Player) sender);
            Entry<Scoreboard, Boolean> actionMapEntry = boards.get(((Player) sender).getName());
            Scoreboard board = actionMapEntry.getKey();
            if (actionMapEntry.getValue()) {
                ((Player) sender).setScoreboard(Bukkit.getServer().getScoreboardManager().getNewScoreboard());
                boards.put(((Player) sender).getName(), new SimpleEntry<Scoreboard, Boolean>(board, false));
            } else {
                ((Player) sender).setScoreboard(board);
                boards.put(((Player) sender).getName(), new SimpleEntry<Scoreboard, Boolean>(board, true));
            }
        }
        return true;
    }

    static void checkForCompletion(Player p) {
        int completed = 0;
        int all = 0;
        for (Object questIDs : App.main.getConfig().getConfigurationSection("quests").getKeys(false).toArray()) {
            if (App.main.getConfig()
                    .contains("players." + p.getUniqueId().toString() + ".currentQuests." + questIDs.toString())) {
                if (App.main.getConfig().get(
                        "players." + p.getUniqueId().toString() + ".currentQuests." + questIDs.toString() + ".state")
                        .equals("finished")) {
                    completed++;
                }
                all++;
            }
        }
        if (completed == all) {
            if (!App.main.getConfig().get("players." + p.getUniqueId().toString() + ".rewards").equals("claimed")) {

                surpriseBox = new ItemStack(Material.PLAYER_HEAD, 1);
                SkullMeta im = (SkullMeta) surpriseBox.getItemMeta();
                im.displayName(Component.translatable(ChatColor.WHITE + "Überraschungsbox"));
                im.setPlayerProfile(Bukkit.createProfile(UUID.randomUUID(), null));
                PlayerProfile playerProfile = im.getPlayerProfile();
                playerProfile.getProperties().add(new ProfileProperty("textures",
                        "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZDQxZmJlYTljMmQxOTA0MGU1NjdmMzg3YWI0NmIyZjhhM2ExZGE4ZWVjOWQzOTllMmU0YWRjZjA1YWRhOGEyYSJ9fX0="));
                im.setPlayerProfile(playerProfile);
                nsksurpriseBox = new NamespacedKey(App.main, "R3SSurpriseBox");
                im.getPersistentDataContainer().set(nsksurpriseBox, PersistentDataType.STRING, "R3S_SurpriseBox");
                ArrayList<Component> lore = new ArrayList<Component>();
                lore.add(Component.translatable("Quest Belohnung"));
                im.lore(lore);
                surpriseBox.setItemMeta(im);

                Boolean freeSpace = false;
                Boolean given = false;
                for (ItemStack i : p.getInventory().getStorageContents()) {
                    if (i != null) {

                        if (i.getType() == surpriseBox.getType() && i.hasItemMeta()
                                && i.getItemMeta().getPersistentDataContainer() != null) {
                            if (i.getItemMeta().getPersistentDataContainer().has(nsksurpriseBox,
                                    PersistentDataType.STRING)) {
                                if (i.getAmount() < 64) {
                                    i.setAmount(i.getAmount() + 1);
                                    given = true;
                                    break;
                                }
                            }
                        }

                    } else {
                        if (i == null) {
                            freeSpace = true;
                        }
                    }
                }
                if (!freeSpace && !given) {
                    
                    p.sendMessage(helper.R3SMessage(Type.ERROR, "[DailyQuests] Dein Inventar ist voll, schaffe Platz und logge dich ein, deine Questbelohnung zu erhalten!"));
                } else {
                    if (!given && freeSpace) {
                        p.getInventory().addItem(surpriseBox);
                    }
                    p.sendMessage(
                        helper.R3SMessage(Type.SUCCESS,"[DailyQuests] Du hast 1x Überraschungsbox als Questbelohnung erhalten!"));
                    App.main.getConfig().set("players." + p.getUniqueId() + ".rewards", "claimed");
                    App.main.saveConfig();
                }
            }
        }
    }
}
