package com.tiedup.remake.network.labor;

import com.tiedup.remake.network.base.AbstractClientPacket;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;

/**
 * Server-to-Client packet for synchronizing labor task progress.
 * Sent when:
 * - A task is assigned (start)
 * - Progress is made (increment)
 * - A task is completed or cancelled (clear)
 */
public class PacketSyncLaborProgress extends AbstractClientPacket {

    private final boolean hasTask;
    private final String taskDescription;
    private final int progress;
    private final int quota;
    private final int valueEmeralds;

    /**
     * Create a packet with task data.
     */
    public PacketSyncLaborProgress(
        String taskDescription,
        int progress,
        int quota,
        int valueEmeralds
    ) {
        this.hasTask = true;
        this.taskDescription = taskDescription;
        this.progress = progress;
        this.quota = quota;
        this.valueEmeralds = valueEmeralds;
    }

    /**
     * Create a packet to clear the task (no active task).
     */
    public PacketSyncLaborProgress() {
        this.hasTask = false;
        this.taskDescription = "";
        this.progress = 0;
        this.quota = 0;
        this.valueEmeralds = 0;
    }

    /**
     * Encode packet data to buffer.
     */
    public void encode(FriendlyByteBuf buf) {
        buf.writeBoolean(hasTask);
        if (hasTask) {
            buf.writeUtf(taskDescription);
            buf.writeInt(progress);
            buf.writeInt(quota);
            buf.writeInt(valueEmeralds);
        }
    }

    /**
     * Decode packet data from buffer.
     */
    public static PacketSyncLaborProgress decode(FriendlyByteBuf buf) {
        boolean hasTask = buf.readBoolean();
        if (hasTask) {
            String taskDescription = buf.readUtf();
            int progress = buf.readInt();
            int quota = buf.readInt();
            int valueEmeralds = buf.readInt();
            return new PacketSyncLaborProgress(
                taskDescription,
                progress,
                quota,
                valueEmeralds
            );
        } else {
            return new PacketSyncLaborProgress();
        }
    }

    @Override
    @OnlyIn(Dist.CLIENT)
    protected void handleClientImpl() {
        ClientHandler.handle(this);
    }

    @OnlyIn(Dist.CLIENT)
    private static class ClientHandler {

        private static void handle(PacketSyncLaborProgress pkt) {
            if (pkt.hasTask) {
                com.tiedup.remake.client.state.ClientLaborState.setTask(
                    pkt.taskDescription,
                    pkt.progress,
                    pkt.quota,
                    pkt.valueEmeralds
                );
            } else {
                com.tiedup.remake.client.state.ClientLaborState.clearTask();
            }
        }
    }
}
