package com.dairymoose.modernlife.network.play.client;

import com.dairymoose.modernlife.blocks.gui.chess.BishopPiece;
import com.dairymoose.modernlife.blocks.gui.chess.ChessScreen;
import com.dairymoose.modernlife.blocks.gui.chess.KingPiece;
import com.dairymoose.modernlife.blocks.gui.chess.KnightPiece;
import com.dairymoose.modernlife.blocks.gui.chess.PawnPiece;
import com.dairymoose.modernlife.blocks.gui.chess.Piece;
import com.dairymoose.modernlife.blocks.gui.chess.PieceIds;
import com.dairymoose.modernlife.blocks.gui.chess.QueenPiece;
import com.dairymoose.modernlife.blocks.gui.chess.RookPiece;
import com.dairymoose.modernlife.core.CustomBlocks;
import com.dairymoose.modernlife.core.ModernLifeCommon;
import com.dairymoose.modernlife.tileentities.ChessBoardBlockEntity;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Supplier;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.Tag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.game.ServerGamePacketListener;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.network.ServerGamePacketListenerImpl;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.network.NetworkEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/* loaded from: outputsrg.jar:com/dairymoose/modernlife/network/play/client/ServerboundChessStatePacket.class */
public class ServerboundChessStatePacket implements Packet<ServerGamePacketListener> {
    public int currentTurn;
    public int newCheckState;
    public String whitePlayer;
    public String blackPlayer;
    public boolean isWhiteTurn;
    public List<Piece> whitePieces;
    public List<Piece> blackPieces;
    public Piece movedPiece;
    private BlockPos chessBoardPos;
    public ChessScreen.CastleFlags castleFlags;
    private static final Logger LOGGER = LogManager.getLogger();

    public ServerboundChessStatePacket() {
    }

    public ServerboundChessStatePacket(FriendlyByteBuf buffer) {
        read(buffer);
    }

    public ServerboundChessStatePacket(int currentTurn, int newCheckState, String whitePlayer, String blackPlayer, boolean isWhiteTurn, BlockPos chessBoardPos, List<Piece> whitePieces, List<Piece> blackPieces, Piece movedPiece, ChessScreen.CastleFlags castleFlags) {
        this.currentTurn = currentTurn;
        this.newCheckState = newCheckState;
        this.whitePlayer = whitePlayer;
        this.blackPlayer = blackPlayer;
        this.isWhiteTurn = isWhiteTurn;
        this.chessBoardPos = chessBoardPos;
        this.whitePieces = whitePieces;
        this.blackPieces = blackPieces;
        this.movedPiece = movedPiece;
        this.castleFlags = castleFlags;
    }

    private void addPieceToList(List<Piece> pieceList, int type, int x, int y) {
        if (type == PieceIds.BISHOP.ordinal()) {
            pieceList.add(new BishopPiece().withXy(x, y));
            return;
        }
        if (type == PieceIds.KING.ordinal()) {
            pieceList.add(new KingPiece().withXy(x, y));
            return;
        }
        if (type == PieceIds.KNIGHT.ordinal()) {
            pieceList.add(new KnightPiece().withXy(x, y));
            return;
        }
        if (type == PieceIds.PAWN.ordinal()) {
            pieceList.add(new PawnPiece().withXy(x, y));
        } else if (type == PieceIds.QUEEN.ordinal()) {
            pieceList.add(new QueenPiece().withXy(x, y));
        } else if (type == PieceIds.ROOK.ordinal()) {
            pieceList.add(new RookPiece().withXy(x, y));
        }
    }

    public void read(FriendlyByteBuf packet) {
        this.whitePieces = new ArrayList();
        this.blackPieces = new ArrayList();
        this.currentTurn = packet.readInt();
        this.newCheckState = packet.readInt();
        this.whitePlayer = packet.readUtf(40);
        this.blackPlayer = packet.readUtf(40);
        this.isWhiteTurn = packet.readBoolean();
        this.chessBoardPos = packet.readBlockPos();
        int whiteCount = packet.readInt();
        for (int i = 0; i < whiteCount; i++) {
            int type = packet.readInt();
            int x = packet.readInt();
            int y = packet.readInt();
            addPieceToList(this.whitePieces, type, x, y);
        }
        int blackCount = packet.readInt();
        for (int i2 = 0; i2 < blackCount; i2++) {
            int type2 = packet.readInt();
            int x2 = packet.readInt();
            int y2 = packet.readInt();
            addPieceToList(this.blackPieces, type2, x2, y2);
        }
        int type3 = packet.readInt();
        int x3 = packet.readInt();
        int y3 = packet.readInt();
        List<Piece> movedPieces = new ArrayList<>();
        addPieceToList(movedPieces, type3, x3, y3);
        if (movedPieces.size() == 1) {
            this.movedPiece = movedPieces.get(0);
        }
        if (this.castleFlags == null) {
            this.castleFlags = new ChessScreen.CastleFlags();
        }
        this.castleFlags.blackKingHasMoved = packet.readBoolean();
        this.castleFlags.blackLeftRookHasMoved = packet.readBoolean();
        this.castleFlags.blackRightRookHasMoved = packet.readBoolean();
        this.castleFlags.whiteKingHasMoved = packet.readBoolean();
        this.castleFlags.whiteLeftRookHasMoved = packet.readBoolean();
        this.castleFlags.whiteRightRookHasMoved = packet.readBoolean();
    }

    public void write(FriendlyByteBuf packet) {
        packet.writeInt(this.currentTurn);
        packet.writeInt(this.newCheckState);
        if (this.whitePlayer != null) {
            packet.writeUtf(this.whitePlayer);
        } else {
            packet.writeUtf("");
        }
        if (this.blackPlayer != null) {
            packet.writeUtf(this.blackPlayer);
        } else {
            packet.writeUtf("");
        }
        packet.writeBoolean(this.isWhiteTurn);
        packet.writeBlockPos(this.chessBoardPos);
        packet.writeInt(this.whitePieces.size());
        for (Piece p : this.whitePieces) {
            packet.writeInt(p.getId());
            packet.writeInt(p.f9x);
            packet.writeInt(p.f10y);
        }
        packet.writeInt(this.blackPieces.size());
        for (Piece p2 : this.blackPieces) {
            packet.writeInt(p2.getId());
            packet.writeInt(p2.f9x);
            packet.writeInt(p2.f10y);
        }
        if (this.movedPiece != null) {
            packet.writeInt(this.movedPiece.getId());
            packet.writeInt(this.movedPiece.f9x);
            packet.writeInt(this.movedPiece.f10y);
        } else {
            packet.writeInt(-1);
            packet.writeInt(0);
            packet.writeInt(0);
        }
        packet.writeBoolean(this.castleFlags.blackKingHasMoved);
        packet.writeBoolean(this.castleFlags.blackLeftRookHasMoved);
        packet.writeBoolean(this.castleFlags.blackRightRookHasMoved);
        packet.writeBoolean(this.castleFlags.whiteKingHasMoved);
        packet.writeBoolean(this.castleFlags.whiteLeftRookHasMoved);
        packet.writeBoolean(this.castleFlags.whiteRightRookHasMoved);
    }

    public static ServerboundChessStatePacket fromNbt(CompoundTag nbt) {
        ServerboundChessStatePacket packet = new ServerboundChessStatePacket();
        packet.whitePieces = new ArrayList();
        packet.blackPieces = new ArrayList();
        if (nbt.contains("BoardState")) {
            CompoundTag boardState = nbt.getCompound("BoardState");
            packet.currentTurn = boardState.getInt("CurrentTurn");
            packet.newCheckState = boardState.getInt("NewCheckState");
            packet.whitePlayer = boardState.getString("WhitePlayer");
            packet.blackPlayer = boardState.getString("BlackPlayer");
            packet.isWhiteTurn = boardState.getBoolean("IsWhiteTurn");
            if (packet.castleFlags == null) {
                packet.castleFlags = new ChessScreen.CastleFlags();
            }
            packet.castleFlags.blackKingHasMoved = boardState.getBoolean("BlackKingHasMoved");
            packet.castleFlags.blackLeftRookHasMoved = boardState.getBoolean("BlackLeftRookHasMoved");
            packet.castleFlags.blackRightRookHasMoved = boardState.getBoolean("BlackRightRookHasMoved");
            packet.castleFlags.whiteKingHasMoved = boardState.getBoolean("WhiteKingHasMoved");
            packet.castleFlags.whiteLeftRookHasMoved = boardState.getBoolean("WhiteLeftRookHasMoved");
            packet.castleFlags.whiteRightRookHasMoved = boardState.getBoolean("WhiteRightRookHasMoved");
            CompoundTag compoundTag = boardState.get("MovedPiece");
            if (compoundTag instanceof CompoundTag) {
                CompoundTag item = compoundTag;
                int type = item.getInt("id");
                int x = item.getInt("x");
                int y = item.getInt("y");
                List<Piece> movedPieces = new ArrayList<>();
                packet.addPieceToList(movedPieces, type, x, y);
                if (movedPieces.size() == 1) {
                    packet.movedPiece = movedPieces.get(0);
                }
            }
            if (boardState.contains("WhitePieces")) {
                ListTag listTag = boardState.get("WhitePieces");
                if (listTag instanceof ListTag) {
                    ListTag list = listTag;
                    Iterator<Tag> it = list.iterator();
                    while (it.hasNext()) {
                        Tag next = it.next();
                        if (next instanceof CompoundTag) {
                            CompoundTag item2 = (CompoundTag) next;
                            if (item2.contains("id") && item2.contains("x") && item2.contains("y")) {
                                int type2 = item2.getInt("id");
                                int x2 = item2.getInt("x");
                                int y2 = item2.getInt("y");
                                packet.addPieceToList(packet.whitePieces, type2, x2, y2);
                            } else {
                                return packet;
                            }
                        }
                    }
                }
            }
            if (boardState.contains("BlackPieces")) {
                ListTag listTag2 = boardState.get("BlackPieces");
                if (listTag2 instanceof ListTag) {
                    ListTag list2 = listTag2;
                    Iterator<Tag> it2 = list2.iterator();
                    while (it2.hasNext()) {
                        Tag next2 = it2.next();
                        if (next2 instanceof CompoundTag) {
                            CompoundTag item3 = (CompoundTag) next2;
                            if (item3.contains("id") && item3.contains("x") && item3.contains("y")) {
                                int type3 = item3.getInt("id");
                                int x3 = item3.getInt("x");
                                int y3 = item3.getInt("y");
                                packet.addPieceToList(packet.blackPieces, type3, x3, y3);
                            } else {
                                return packet;
                            }
                        }
                    }
                }
            }
        }
        return packet;
    }

    public CompoundTag getPieceNbt(Piece piece) {
        CompoundTag nbt = new CompoundTag();
        nbt.putInt("id", piece.getId());
        nbt.putInt("x", piece.f9x);
        nbt.putInt("y", piece.f10y);
        return nbt;
    }

    public void writeToNbt(CompoundTag nbt) {
        CompoundTag boardState = new CompoundTag();
        ListTag whiteNbt = new ListTag();
        for (Piece p : this.whitePieces) {
            whiteNbt.add(getPieceNbt(p));
        }
        ListTag blackNbt = new ListTag();
        for (Piece p2 : this.blackPieces) {
            blackNbt.add(getPieceNbt(p2));
        }
        boardState.put("WhitePieces", whiteNbt);
        boardState.put("BlackPieces", blackNbt);
        boardState.putInt("CurrentTurn", this.currentTurn);
        boardState.putInt("NewCheckState", this.newCheckState);
        boardState.putString("WhitePlayer", this.whitePlayer);
        boardState.putString("BlackPlayer", this.blackPlayer);
        boardState.putBoolean("IsWhiteTurn", this.isWhiteTurn);
        boardState.putBoolean("BlackKingHasMoved", this.castleFlags.blackKingHasMoved);
        boardState.putBoolean("BlackLeftRookHasMoved", this.castleFlags.blackLeftRookHasMoved);
        boardState.putBoolean("BlackRightRookHasMoved", this.castleFlags.blackRightRookHasMoved);
        boardState.putBoolean("WhiteKingHasMoved", this.castleFlags.whiteKingHasMoved);
        boardState.putBoolean("WhiteLeftRookHasMoved", this.castleFlags.whiteLeftRookHasMoved);
        boardState.putBoolean("WhiteRightRookHasMoved", this.castleFlags.whiteRightRookHasMoved);
        if (this.movedPiece != null) {
            boardState.put("MovedPiece", getPieceNbt(this.movedPiece));
        }
        nbt.put("BoardState", boardState);
    }

    public void handle(Supplier<NetworkEvent.Context> ctx) {
        ctx.get().enqueueWork(() -> {
            ((NetworkEvent.Context) ctx.get()).getSender();
            handle((ServerGamePacketListener) ((NetworkEvent.Context) ctx.get()).getNetworkManager().getPacketListener());
        });
        ctx.get().setPacketHandled(true);
    }

    public void handle(ServerGamePacketListener p_148833_1_) {
        BlockState chessBoardState;
        ModernLifeCommon.LOGGER.debug("Handle ServerboundChessStatePacket");
        if (this.chessBoardPos != null && (p_148833_1_ instanceof ServerGamePacketListenerImpl)) {
            ServerGamePacketListenerImpl serverHandler = (ServerGamePacketListenerImpl) p_148833_1_;
            ServerLevel level = serverHandler.player.getLevel();
            if (level != null && level.isLoaded(this.chessBoardPos) && (chessBoardState = level.getBlockState(this.chessBoardPos)) != null && chessBoardState.is(CustomBlocks.BLOCK_CHESS_BOARD.get())) {
                BlockEntity tileEntity = level.getChunkAt(this.chessBoardPos).getBlockEntity(this.chessBoardPos);
                if (tileEntity instanceof ChessBoardBlockEntity) {
                    ChessBoardBlockEntity chessBoardBlockEntity = (ChessBoardBlockEntity) tileEntity;
                    ItemStack currentItem = chessBoardBlockEntity.getItem(0);
                    if (chessBoardBlockEntity != null) {
                        writeToNbt(currentItem.getOrCreateTag());
                        level.sendBlockUpdated(this.chessBoardPos, chessBoardState, chessBoardState, 2);
                    }
                }
            }
        }
    }
}
