package dev.drawethree.xprison.gems.service.impl;

import dev.drawethree.xprison.XPrison;
import dev.drawethree.xprison.gems.repo.GemsRepository;
import dev.drawethree.xprison.gems.service.GemsService;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;

import java.util.Map;
import java.util.UUID;
import java.util.function.Consumer;

public class GemsServiceImpl implements GemsService {

	private final GemsRepository repository;
	private final XPrison plugin; // Reference to your main plugin instance

	public GemsServiceImpl(GemsRepository repository, XPrison plugin) {
		this.repository = repository;
		this.plugin = plugin; // Initialize the plugin reference
	}

	@Override
	public long getPlayerGems(OfflinePlayer player) {
		return repository.getPlayerGems(player);
	}

	@Override
	public void setGems(OfflinePlayer player, long newAmount) {
		repository.updateGems(player, newAmount);
	}

	@Override
	public Map<UUID, Long> getTopGems(int amountOfRecords) {
		return repository.getTopGems(amountOfRecords);
	}

	@Override
	public void createGems(OfflinePlayer player, long startingGems) {
		repository.addIntoGems(player, startingGems);
	}

	@Override
	public void updateGemsAsync(OfflinePlayer player, long newAmount, Consumer<Boolean> callback) {
		Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
			try {
				// Assuming there's a method in the repository to perform the update
				repository.updateGems(player, newAmount);

				// If the operation is successful, invoke the callback with true
				Bukkit.getScheduler().runTask(plugin, () -> callback.accept(true));
			} catch (Exception e) {
				// Log the exception and invoke the callback with false in case of failure
				plugin.getLogger().warning("Failed to update gems asynchronously for " + player.getName() + ": " + e.getMessage());
				Bukkit.getScheduler().runTask(plugin, () -> callback.accept(false));
			}
		});
	}
}
