package com.zivilon.cinder_loe.network;

import com.zivilon.cinder_loe.carriage.CarriageDestination;
import com.zivilon.cinder_loe.carriage.CarriageDestinationsData;
import com.zivilon.cinder_loe.carriage.CarriageUtils;
import com.zivilon.cinder_loe.carriage.gui.CarriageCoinUtil;
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 lotr.common.network.LOTRPacketHandler;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.world.WorldServer;

public class PacketCarriageSelect implements IMessage {
    private String destinationName;

    public PacketCarriageSelect() {}

    public PacketCarriageSelect(String destinationName) {
        this.destinationName = destinationName;
    }

    @Override
    public void toBytes(ByteBuf buf) {
        ByteBufUtils.writeUTF8String(buf, destinationName);
    }

    @Override
    public void fromBytes(ByteBuf buf) {
        destinationName = ByteBufUtils.readUTF8String(buf);
    }

    public static class Handler implements IMessageHandler<PacketCarriageSelect, IMessage> {
        @Override
        public IMessage onMessage(PacketCarriageSelect msg, MessageContext ctx) {
            EntityPlayerMP player = ctx.getServerHandler().playerEntity;
            WorldServer world = player.getServerForPlayer();
            CarriageDestinationsData data = CarriageDestinationsData.get(world);

            CarriageDestination dest = data.getDestinations().get(msg.destinationName);
            if (dest != null) {
                int cost = CarriageUtils.calculateCost(player.posX, player.posZ, dest);

                if (CarriageCoinUtil.removeCoinsAndGiveChange(player, cost)) {
                    if (player.dimension != dest.dimension) {
                        MinecraftServer.getServer().getConfigurationManager().transferPlayerToDimension(player, dest.dimension);
                    }
                    player.setPositionAndUpdate(dest.x + 0.5, dest.y, dest.z + 0.5);
                    world.playSoundEffect(dest.x, dest.y, dest.z, "lotr:event.trade", 1.0F, 1.0F);

                    // Send fade packet to client
                    //LOTRPacketHandler.networkWrapper.sendTo(new PacketCarriageFTB(), (EntityPlayerMP) player);

                    String displayName = dest.name.replace("\"", "");
                    player.addChatMessage(new ChatComponentText(EnumChatFormatting.YELLOW + "You have arrived at " + displayName + "..."));
                } else {
                    player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "Not enough coins!"));
                }
            }
            return null;
        }
    }


}
