package net.cobem.grizzly.communication.events.rooms;

import net.cobem.grizzly.Grizzly;
import net.cobem.grizzly.communication.EventRequest;
import net.cobem.grizzly.communication.GameEvent;
import net.cobem.grizzly.communication.composers.rooms.UpdateFloorItemComposer;
import net.cobem.grizzly.habbohotel.pathfinding.Position;
import net.cobem.grizzly.habbohotel.rooms.Room;
import net.cobem.grizzly.habbohotel.rooms.items.FloorItem;
import net.cobem.grizzly.habbohotel.sessions.Session;

public class ItemPositionChangeEvent implements GameEvent {

    @Override
    public void compose(Session Session, EventRequest Request) {
        if (!Session.getActor().CurrentRoom.getRightHolders().contains(Session.getHabbo().getID())) {
            Grizzly.write(Session.getHabbo().getUsername() + " tried to move something!");
            return;
        }

        Room mRoom = Session.getActor().CurrentRoom;

        int ID = Request.readInt();
        int X = Request.readInt();
        int Y = Request.readInt();
        int Rotation = Request.readInt();

        FloorItem Item = mRoom.getFloors().get(ID);

        if (Item == null) {
            return;
        }

        if (mRoom.nonStackableTile((new Position(X, Y, 0)))) {
            return;
        }

        for (Position mPosition : mRoom.getPositions().values()) {
            if (mPosition.X == X && mPosition.Y == Y) {
                return;
            }
        }

        Item.X = X;
        Item.Y = Y;

        Float Z = (float) mRoom.getModel().getTileHeight(X, Y);

        Item.Height = (float) mRoom.getTopHeight(new Position(X, Y, 0), Item);

        Item.Rotation = Rotation;

        Grizzly.getStorage().execute("UPDATE items SET x = '" + Item.X + "', y = '" + Item.Y + "', rot = '" + Item.Rotation + "', z = '" + Item.Height + "' WHERE id = '" + ID + "'");

        mRoom.getFloors().remove(ID);
        mRoom.getFloors().put(ID, new FloorItem(ID));

        mRoom.getMap().ReGenerateCollisionMap();

        Session.getActor().CurrentRoom.sendMessage(UpdateFloorItemComposer.compose(ID, Item, Session.getActor().CurrentRoom.Owner));
    }

}
