package com.zivilon.cinder_loe.network;

import com.zivilon.cinder_loe.carriage.CarriageDestination;
import com.zivilon.cinder_loe.carriage.gui.GuiCarriageMenu;
import cpw.mods.fml.common.network.ByteBufUtils;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
import io.netty.buffer.ByteBuf;
import net.minecraft.client.Minecraft;

import java.util.ArrayList;
import java.util.List;

public class PacketOpenCarriageGui implements IMessage {
    private List<String> names = new ArrayList<>();
    private List<Integer> costs = new ArrayList<>();
    private List<String> road = new ArrayList<>();

    public PacketOpenCarriageGui() {}

    public PacketOpenCarriageGui(List<String> names, List<Integer> costs, List<String> road) {
        this.names = names;
        this.costs = costs;
        this.road = road;
    }

    @Override
    public void toBytes(ByteBuf buf) {
        buf.writeInt(names.size());
        for (int i = 0; i < names.size(); i++) {
            ByteBufUtils.writeUTF8String(buf, names.get(i));
            buf.writeInt(costs.get(i));
            ByteBufUtils.writeUTF8String(buf, road.get(i));
        }
    }

    @Override
    public void fromBytes(ByteBuf buf) {
        int count = buf.readInt();
        for (int i = 0; i < count; i++) {
            names.add(ByteBufUtils.readUTF8String(buf));
            costs.add(buf.readInt());
            road.add(ByteBufUtils.readUTF8String(buf));
        }
    }

    public static class Handler implements IMessageHandler<PacketOpenCarriageGui, IMessage> {
        @Override
        public IMessage onMessage(PacketOpenCarriageGui msg, MessageContext ctx) {
            Minecraft.getMinecraft().func_152344_a(new Runnable() {
                @Override
                public void run() {
                    List<CarriageDestination> dests = new ArrayList<>();
                    for (int i = 0; i < msg.names.size(); i++) {
                        dests.add(new CarriageDestination(msg.names.get(i), 0, 0, 0, 0, msg.road.get(i)));  // dummy pos
                    }
                    Minecraft.getMinecraft().displayGuiScreen(new GuiCarriageMenu(dests, msg.costs));
                }
                });
            return null;
        }
    }
}

