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

package engine.net.client.handlers;

import engine.net.client.ClientConnection;
import engine.net.client.msg.ClientNetMsg;
import engine.net.client.msg.CloseTradeWindowMsg;
import engine.net.client.msg.CommitToTradeMsg;
import engine.objects.CharacterItemManager;
import engine.objects.PlayerCharacter;

import static engine.objects.CharacterItemManager.canTrade;

public class CommitToTradeMsgHandler extends AbstractClientMsgHandler {

    public CommitToTradeMsgHandler() {
        super();
    }

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

        PlayerCharacter source = origin.getPlayerCharacter();

        // Member variable declaration

        CommitToTradeMsg msg;

        // Member variable assignment

        msg = (CommitToTradeMsg) baseMsg;

        if (source == null || !source.isAlive())
            return false;

        source.charItemManager.setTradeCommitted((byte) 1);

        ClientConnection ccOther = source.charItemManager.tradingWith;

        if (ccOther == null)
            return false;

        PlayerCharacter other = ccOther.getPlayerCharacter();

        if (other == null || !other.isAlive())
            return false;

        CharacterItemManager tradingWith = other.charItemManager;

        if (tradingWith == null)
            return false;

        if (!canTrade(source, other))
            return false;

        source.charItemManager.modifyCommitToTrade();

        if (source.charItemManager.getTradeCommitted() == (byte) 1 && tradingWith.getTradeCommitted() == (byte) 1) {
            int tradeID = source.charItemManager.tradeID;
            CloseTradeWindowMsg ctwm1 = new CloseTradeWindowMsg(source, tradeID);
            CloseTradeWindowMsg ctwm2 = new CloseTradeWindowMsg(other, tradeID);
            source.charItemManager.commitTrade();
            source.charItemManager.closeTradeWindow(ctwm1, false);
            other.charItemManager.closeTradeWindow(ctwm2, false);
        }

        return true;
    }

}