// • ▌ ▄ ·.  ▄▄▄·  ▄▄ • ▪   ▄▄· ▄▄▄▄·  ▄▄▄·  ▐▄▄▄  ▄▄▄ .
// ·██ ▐███▪▐█ ▀█ ▐█ ▀ ▪██ ▐█ ▌▪▐█ ▀█▪▐█ ▀█ •█▌ ▐█▐▌·
// ▐█ ▌▐▌▐█·▄█▀▀█ ▄█ ▀█▄▐█·██ ▄▄▐█▀▀█▄▄█▀▀█ ▐█▐ ▐▌▐▀▀▀
// ██ ██▌▐█▌▐█ ▪▐▌▐█▄▪▐█▐█▌▐███▌██▄▪▐█▐█ ▪▐▌██▐ █▌▐█▄▄▌
// ▀▀  █▪▀▀▀ ▀  ▀ ·▀▀▀▀ ▀▀▀·▀▀▀ ·▀▀▀▀  ▀  ▀ ▀▀  █▪ ▀▀▀
//      Magicbane Emulator Project © 2013 - 2022
//                www.magicbane.com

package engine.net.client.handlers;

import engine.gameManager.SessionManager;
import engine.net.client.ClientConnection;
import engine.net.client.msg.ClientNetMsg;
import engine.net.client.msg.login.CommitNewCharacterMsg;
import engine.objects.PlayerCharacter;
import engine.server.MBServerStatics;
import engine.server.login.LoginServer;
import org.pmw.tinylog.Logger;

public class CommitNewCharacterMsgHandler extends AbstractClientMsgHandler {

    public CommitNewCharacterMsgHandler() {
        super();
    }

    @Override
    protected boolean _handleNetMsg(ClientNetMsg baseMsg, ClientConnection origin) {

        if (origin.getAccount() == null)
            return true;

        CommitNewCharacterMsg msg = (CommitNewCharacterMsg) baseMsg;

        try {
            // Check to see if there is an available slot.
            if (origin.getAccount().characterMap.size() >= MBServerStatics.MAX_NUM_OF_CHARACTERS) {
                LoginServer.sendCharacterSelectScreen(SessionManager.getSession(origin));
                return true;
            }

            PlayerCharacter newPlayer = PlayerCharacter.generatePCFromCommitNewCharacterMsg(origin.getAccount(), msg, origin);

            if (newPlayer == null) {
                Logger.info("Player returned null while creating character.");
                LoginServer.sendCharacterSelectScreen(SessionManager.getSession(origin), true);
                return true;
            }

            PlayerCharacter.initializePlayer(newPlayer);
            origin.getAccount().characterMap.putIfAbsent(newPlayer.getObjectUUID(), newPlayer);

            // Send back to Character Select Screen
            LoginServer.sendCharacterSelectScreen(SessionManager.getSession(origin), true);

        } catch (Exception e) {
            Logger.error(e);
            LoginServer.sendCharacterSelectScreen(SessionManager.getSession(origin), true);
        }

        return true;
    }

}