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

package engine.net.client.handlers;

import engine.gameManager.ConfigManager;
import engine.gameManager.DbManager;
import engine.gameManager.SessionManager;
import engine.mbEnums;
import engine.net.client.ClientConnection;
import engine.net.client.msg.ClientNetMsg;
import engine.net.client.msg.login.ClientLoginInfoMsg;
import engine.objects.Account;
import engine.objects.PlayerCharacter;
import engine.server.MBServerStatics;
import engine.server.login.LoginServer;
import engine.session.Session;
import org.pmw.tinylog.Logger;

public class ClientLoginInfoMsgHandler extends AbstractClientMsgHandler {

    public ClientLoginInfoMsgHandler() {
        super();
    }

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

        PlayerCharacter playerCharacter = origin.getPlayerCharacter();

        // Member variable declaration

        ClientLoginInfoMsg msg;

        // Member variable assignment

        msg = (ClientLoginInfoMsg) baseMsg;

        // Add zero length strings to eliminate the need for null checking.
        String uname = msg.getUname();
        String pass = msg.getPword();

        // Check to see if there is actually any data in uname.pass
        if (uname.length() == 0) {
            LoginServer.KickToLogin(MBServerStatics.LOGINERROR_UNABLE_TO_LOGIN, "The username provided was zero length.", origin);
            return true;
        }

        if (pass.length() == 0) {
            LoginServer.KickToLogin(MBServerStatics.LOGINERROR_UNABLE_TO_LOGIN, "The password provided was zero length.", origin);
            return true;
        }

        if (LoginServer.loginServerRunning == false) {
            LoginServer.KickToLogin(MBServerStatics.LOGINERROR_LOGINSERVER_BUSY, "", origin);
            return true;
        }

        Account account;

        account = DbManager.AccountQueries.GET_ACCOUNT(uname);

        // Create the account if it doesn't exist and MB_LOGIN_AUTOREG is TRUE;
        // This is to support MagicBox users without a web hosting skillset.

        if (account == null) {

            if (ConfigManager.MB_LOGIN_AUTOREG.getValue().equalsIgnoreCase("false")) {
                LoginServer.KickToLogin(MBServerStatics.LOGINERROR_INVALID_USERNAME_PASSWORD, "Could not find account (" + uname + ')', origin);
                Logger.info("Could not find account (" + uname + ')');
                return true;
            }

            Logger.info("AutoRegister: " + uname + "/" + pass);
            DbManager.AccountQueries.CREATE_SINGLE(uname, pass);
            account = DbManager.AccountQueries.GET_ACCOUNT(uname);

            if (account == null) {
                LoginServer.KickToLogin(MBServerStatics.LOGINERROR_INVALID_USERNAME_PASSWORD, "Could not find account (" + uname + ')', origin);
                Logger.info("Could not auto-create (" + uname + ')');
                return true;
            }
        }

        if (account.getLastLoginFailure() + MBServerStatics.RESET_LOGIN_ATTEMPTS_AFTER < System.currentTimeMillis())
            account.resetLoginAttempts();

        // TODO: Log the login attempts IP, name, password and timestamp
        // Check number invalid login attempts. If 5 or greater, kick to login.
        if (account.getLoginAttempts() >= MBServerStatics.MAX_LOGIN_ATTEMPTS) {

            LoginServer.KickToLogin(MBServerStatics.LOGINERROR_UNABLE_TO_LOGIN, "Too many login in attempts for '" + uname + '\'', origin);
            Logger.info("Too many login in attempts for '" + uname + '\'');
            return true;
        }

        if (account.lastPasswordCheck < System.currentTimeMillis()) {
            account.lastPasswordCheck = System.currentTimeMillis() + MBServerStatics.ONE_MINUTE;
        }

        // Attempt to validate login
        try {
            if (!account.passIsValid(pass, origin.getClientIpAddress(), origin.machineID)) {

                account.incrementLoginAttempts();
                LoginServer.KickToLogin(MBServerStatics.LOGINERROR_INVALID_USERNAME_PASSWORD, "", origin);
                Logger.info("Incorrect password(" + uname + ')');
                return true;
            }
        } catch (IllegalArgumentException e1) {
            LoginServer.KickToLogin(MBServerStatics.LOGINERROR_UNABLE_TO_LOGIN, "", origin);
            Logger.info("Failed forum account validation(" + uname + ')');
        }

        // Account deactivated

        if (account.status.equals(mbEnums.AccountStatus.BANNED)) {
            LoginServer.KickToLogin(MBServerStatics.LOGINERROR_NO_MORE_PLAYTIME_ON_ACCOUNT, "", origin);
            return true;
        }

        // Check to see if we have a Session mapped with this Account:
        Session session = SessionManager.getSession(account);

        // If there is, then the account is in use and must be handled:
        // kick the 'other connection'
        if (session != null)
            LoginServer.KickToLogin(MBServerStatics.LOGINERROR_UNABLE_TO_LOGIN, "Your account has been accessed from a different IP & Port.", session.getConn()); // Logout the character


        // TODO implement character logout
        // Get a new session
        session = SessionManager.getNewSession(account, origin);

        // Set Invalid Login Attempts to 0
        account.resetLoginAttempts();

        // Send Login Response
        ClientLoginInfoMsg loginResponse = new ClientLoginInfoMsg(msg);
        loginResponse.setUnknown06(8323072);
        loginResponse.setUnknown07(3276800);
        loginResponse.setUnknown08(196608);
        loginResponse.setUnknown09((short) 15);

        origin.sendMsg(loginResponse);

        // send character select screen
        try {
            LoginServer.sendCharacterSelectScreen(session);
        } catch (Exception e) {
            Logger.error("Unable to Send Character Select Screen to client");
            LoginServer.KickToLogin(MBServerStatics.LOGINERROR_UNABLE_TO_LOGIN, "Unable to send Character Select Screen to client.", origin);
            return true;
        }

        // Logging
        String addyPort = origin.getRemoteAddressAndPortAsString();
        int id = account.getObjectUUID();

        Logger.info(uname + '(' + id + ") has successfully logged in from " + addyPort);

        return true;
    }

}