package me.km.playerbank;

import me.hammerle.snuviscript.code.ISnuviLogger;
import me.km.overrides.ModEntityPlayerMP;
import net.minecraftforge.eventbus.api.EventPriority;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;

public class PlayerManager {
    private final ISnuviLogger logger;
    private final IPlayerBank bank;

    public PlayerManager(ISnuviLogger logger, IPlayerBank bank) {
        this.logger = logger;
        this.bank = bank;
    }

    @SubscribeEvent(priority = EventPriority.HIGH)
    public void onPlayerJoin(PlayerEvent.PlayerLoggedInEvent e) {
        ModEntityPlayerMP p = (ModEntityPlayerMP) e.getPlayer();
        if(p == null) {
            return;
        }

        int id = bank.getId(p.getUniqueID());
        if(id == -1) {
            bank.add(p.getUniqueID(), p.getName().getUnformattedComponentText());
            logger.print(String.format("'%s' was added", p.getName().getString()));

            id = bank.getId(p.getUniqueID());
            if(id == -1) {
                // this should never happen
                logger.print(String.format("'%s' has no id", p.getName().getString()));
            } else {
                p.setId(id);
            }
        } else {
            p.setId(id);
            bank.changeName(p.getUniqueID(), p.getName().getString());
        }
    }
}
