import * as mc from "@minecraft/server";
import * as blocklib from "../sgs_cake_block_lib";

const BLOCK_ENTITY = "sgs_cake:seat_dummy";

export class sittableManager {

    static interact(data) {
        const block = data.block;
        const player = data.player;
        const location = block.center();

        const display_entity = getDisplayEntity(block);

        //only seat a player if the seat is available
        if (display_entity == undefined) {

            let offset = 0;
            if (block.hasTag("sgs_cake_sit_stool")) offset = 0.2;

            const targetLocation = { x: location.x, y: location.y + offset, z: location.z };
            const display_entity = mc.world.getDimension(player.dimension.id).spawnEntity(BLOCK_ENTITY, targetLocation);
            const direction = data.block.permutation.getState("minecraft:cardinal_direction");
            switch (direction) {
                case "north":
                    display_entity.teleport(
                        targetLocation, 
                        {
                            facingLocation: { x: targetLocation.x, y: targetLocation.y, z: targetLocation.z + 1 },
                        }
                    );
                    break;
                case "east":
                    display_entity.teleport(
                        targetLocation, 
                        {
                            facingLocation: { x: targetLocation.x - 1, y: targetLocation.y, z: targetLocation.z },
                        }
                    );
                    break;
                case "south":
                    display_entity.teleport(
                        targetLocation, 
                        {
                            facingLocation: { x: targetLocation.x, y: targetLocation.y, z: targetLocation.z - 1 },
                        }
                    );
                    break;
                case "west":
                    display_entity.teleport(
                        targetLocation, 
                        {
                            facingLocation: { x: targetLocation.x + 1, y: targetLocation.y, z: targetLocation.z },
                        }
                    );
                    break;
                default:
                    break;
            }

            const rideable = display_entity.getComponent('minecraft:rideable');
            rideable.addRider(player);
        }
    }

    //clean up connections made in case this block breaks
    static destroy(data) {
        const block = data.block;
        blocklib.clearDisplay(block);
    }
}


function getDisplayEntity(block) {
    const location = block.center();
    return mc.world.getDimension(block.dimension.id).getEntities({ location, families: ["sgs_cake_display"], maxDistance: 0.3 })[0];
}
