package de.hessj.environmentex;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;

import de.hessj.helper.Helper.Type;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.title.Title;

public class LoginListener implements Listener {
    public static File customYml = new File(App.main.getDataFolder() + "/players.yml");
    public static FileConfiguration customConfig = YamlConfiguration.loadConfiguration(customYml);
    public de.hessj.helper.Helper helper= new de.hessj.helper.Helper();

    @EventHandler
    public void onLogin(PlayerJoinEvent e) {

        App.main.hmActionbar.put(e.getPlayer(), true);

        e.getPlayer().discoverRecipes(App.main.recipeKeys);
        AFKListener.createAFKTimer(e.getPlayer());

        e.joinMessage(null);
        if (!customConfig.contains("players." + e.getPlayer().getUniqueId())) {
            customConfig.set("players." + e.getPlayer().getUniqueId() + ".name", e.getPlayer().getName());
            customConfig.set("players." + e.getPlayer().getUniqueId() + ".firstlogin",
                    (DateTimeFormatter.ofPattern("dd.MM.YYYY-HH:mm:ss")).format(LocalDateTime.now()));
            customConfig.set("players." + e.getPlayer().getUniqueId() + ".whitelisted", false);
            customConfig.set("players." + e.getPlayer().getUniqueId() + ".hasSeenTutorial", false);
            saveCustomYml(customConfig, customYml);
        }
        if (customConfig.getBoolean("players." + e.getPlayer().getUniqueId() + ".whitelisted")) {
            if (!customConfig.getBoolean("players." + e.getPlayer().getUniqueId() + ".hasSeenTutorial")) {
                e.getPlayer().showTitle(Title.title(Component.text("Willkommen!"),
                        Component.text("Eine Übersicht der extra Features findest du auf der Website!")));
                customConfig.set("players." + e.getPlayer().getUniqueId() + ".hasSeenTutorial", true);
                saveCustomYml(customConfig, customYml);
            }


            for (Player p : Bukkit.getOnlinePlayers()) {
                if (p != e.getPlayer()) {
                    p.sendMessage(helper.R3SMessage(Type.INFO, e.getPlayer().getName() + " hat das Spiel betreten."));
                }
            }
        } else {
            e.getPlayer().kick(Component.text("Bitte wende dich an den Administrator um dich freischalten zu lassen!"));
        }
    }

    public static void saveCustomYml(FileConfiguration ymlConfig, File ymlFile) {
        try {
            ymlConfig.save(ymlFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
