package minecraft_mod_player_statistics.src.main.java;

import minecraft_mod_player_statistics.src.main.java.DatabaseManager;

import net.minecraft.world.entity.player.Player;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.living.LivingDeathEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.Instant;
import java.util.UUID;

@Mod("playerstats")
public class PlayerStatisticsMod {
    private final DatabaseManager dbManager;

    public PlayerStatisticsMod() {
        dbManager = new DatabaseManager();
        dbManager.initializeDatabase();
        MinecraftForge.EVENT_BUS.register(this);
    }

    @SubscribeEvent
    public void onBlockBreak(BlockEvent.BreakEvent event) {
        if (event.getPlayer() != null) {
            dbManager.recordStat(event.getPlayer().getUUID(),
                          "block_mined",
                          1,
                          event.getState().getBlock().getRegistryName().toString());
        }
    }

    @SubscribeEvent
    public void onHarvest(PlayerEvent.ItemPickupEvent event) {
        dbManager.recordStat(event.getPlayer().getUUID(),
                  "item_harvested",
                  event.getStack().getCount(),
                  event.getStack().getItem().getRegistryName().toString());
    }

    @SubscribeEvent
    public void onPlayerDeath(LivingDeathEvent event) {
        if (event.getEntity() instanceof Player) {
            Player player = (Player) event.getEntity();
            dbManager.recordStat(player.getUUID(), "death", 1, null);
        }
    }

    @SubscribeEvent
    public void onPlayerTick(PlayerEvent.PlayerLoggedInEvent event) {
        dbManager.recordLocation(event.getPlayer());
    }
}