import { Vector3, distance, distanceSquared, cross } from "./vector3";
import * as game from "./game";

export async function onScriptEventReceive(event) {

    const book = event.sourceEntity;
    if (event.id === "tcs_cba:open_book")
    {
        const player = (await game.getPlayerInLocation(book.dimension, book.location))[0];
        if (!player.hasTag("tcs_cba_book_viewed"))
        {
            player.addTag("tcs_cba_book_viewed");
            await game.tellraw(player, "@s", "§l§aWelcome to Craftable Bases Add-On 2.0§f");
        }
        return;
    }

    // book entity hurt by player
    const player = (await game.getPlayerInLocation(book.dimension, book.location))[0];

    const hitDistance = distance(book.location, player.location);
    const lookDirection = new Vector3(player.getViewDirection());
    const hitPoint = lookDirection.multiply(hitDistance).add(player.location);

    const right = cross(book.getViewDirection(), {x: 0, y: 1, z: 0});
    const rightPoint = new Vector3(book.location).add(right);
    const leftPoint = new Vector3(book.location).subtract(right);
    if(distanceSquared(rightPoint, hitPoint) < distanceSquared(leftPoint, hitPoint)) {
        book.triggerEvent("tcs_cba:turn_page_left");
    } else {
        book.triggerEvent("tcs_cba:turn_page_right");
    }
}
