import * as mc from "@minecraft/server"

export function getRandomInt(min, max) {
    // Ensure that min and max are integers
    min = Math.ceil(min);
    max = Math.floor(max);
    // Generate random integer between min (inclusive) and max (inclusive)
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

export function entityDetectArrow(entity, detectionRadius) {
    const dimension = entity.dimension;

    // Get all arrows within the specified radius
    const arrows = dimension.getEntities({
        location: entity.location,
        maxDistance: detectionRadius,
        type: "minecraft:arrow"
    });

    // Filter out stationary arrows
    const movingArrows = arrows.filter((nPArrow) => {
        const velocity = nPArrow.getVelocity();
        return velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0;
    });

    // Return true if any moving arrows are found
    return movingArrows.length > 0;
}

export function entityDetectAllArrow(entity, detectionRadius) {
    const dimension = entity.dimension;

    // Get all arrows within the specified radius
    const projectiles = dimension.getEntities({
        location: entity.location,
        maxDistance: detectionRadius,
        type: "minecraft:arrow"
    });

    // Filter out stationary arrows
    const movingProjectiles = projectiles.filter((nPArrow) => {
        const velocity = nPArrow.getVelocity();
        return velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0;
    });

    // Return true if any moving arrows are found
    return movingProjectiles;
}

export function entityDetectAllSmallFireball(entity, detectionRadius) {
    const dimension = entity.dimension;

    // Get all arrows within the specified radius
    const projectiles = dimension.getEntities({
        location: entity.location,
        maxDistance: detectionRadius,
        type: "minecraft:small_fireball"
    });

    // Filter out stationary arrows
    const movingProjectiles = projectiles.filter((nPArrow) => {
        const velocity = nPArrow.getVelocity();
        return velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0;
    });

    // Return true if any moving arrows are found
    return movingProjectiles;
}

export function entityDetectAllLargeFireball(entity, detectionRadius) {
    const dimension = entity.dimension;

    // Get all arrows within the specified radius
    const projectiles = dimension.getEntities({
        location: entity.location,
        maxDistance: detectionRadius,
        type: "minecraft:fireball"
    });

    // Filter out stationary arrows
    const movingProjectiles = projectiles.filter((nPArrow) => {
        const velocity = nPArrow.getVelocity();
        return velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0;
    });

    // Return true if any moving arrows are found
    return movingProjectiles;
}

// export function teleportEntityToRandomBlock(entity, radius) {
//     const currentPos = entity.location;

//     // Generate random offsets within the radius
//     const randomX = Math.floor(Math.random() * (radius * 2 + 1)) - radius;
//     const randomZ = Math.floor(Math.random() * (radius * 2 + 1)) - radius;

//     // Check for a random Y offset (optional, defaults to ground level)
//     const randomY = 0; // Modify this if you want vertical movement within the radius

//     // Calculate the new position
//     const newX = currentPos.x + randomX;
//     const newY = currentPos.y + randomY;
//     const newZ = currentPos.z + randomZ;

//     // Teleport the entity
//     try {
//         entity.teleport({ x: newX, y: newY, z: newZ }, {
//             facingLocation: currentPos, // Optional: keeps the entity facing the same direction
//             keepVelocity: false,       // Optional: whether to maintain velocity
//         });
//     } catch (error) {
//         return;
//     }
// }


export function teleportEntityToRandomBlock(entity, radius) {
    const currentPos = entity.location;

    // Helper function to check if a block is air
    function isAirBlock(x, y, z) {
        const block = entity.dimension.getBlock({ x, y, z });
        return block && block.typeId === "minecraft:air";
    }

    let attempts = 0;
    const maxAttempts = 20; // Avoid infinite loops by limiting the number of attempts

    while (attempts < maxAttempts) {
        // Generate random offsets within the radius
        const randomX = Math.floor(Math.random() * (radius * 2 + 1)) - radius;
        const randomZ = Math.floor(Math.random() * (radius * 2 + 1)) - radius;

        // Assume teleporting to ground level
        const groundY = currentPos.y; // Adjust if you need to dynamically find the ground
        const newX = currentPos.x + randomX;
        const newZ = currentPos.z + randomZ;

        // Start checking blocks downward from a reasonable height
        for (let offsetY = 0; offsetY <= 5; offsetY++) {
            const newY = groundY + offsetY;
            if (isAirBlock(newX, newY, newZ) && isAirBlock(newX, newY + 1, newZ)) {
                // If both the block and the one above it are air, teleport the entity
                try {
                    entity.teleport({ x: newX, y: newY, z: newZ }, {
                        facingLocation: currentPos, // Optional: keeps the entity facing the same direction
                        keepVelocity: false,       // Optional: whether to maintain velocity
                    });
                    return;
                } catch (error) {
                    console.error("Failed to teleport entity:", error);
                    return;
                }
            }
        }

        attempts++;
    }

    console.warn("Failed to find a valid air block within the radius after several attempts.");
}


export function returnProjectile(projectile) {
    const velocity = projectile.getVelocity();
    projectile.clearVelocity();
    const reversedVelocity = {
        x: -velocity.x,
        y: -velocity.y,
        z: -velocity.z
    };
    const IMPULSE_STRENGTH = 1.5; // Adjust this value to control the force
    projectile.applyImpulse({
        x: reversedVelocity.x * IMPULSE_STRENGTH,
        y: reversedVelocity.y * IMPULSE_STRENGTH,
        z: reversedVelocity.z * IMPULSE_STRENGTH
    });
}

export function isEntityHappy(entity) {
    let isTired = entity.getProperty("property:tired");
    let isHungry = entity.getProperty("property:hungry");
    let isScared = entity.getProperty("property:scared");
    let isQuest = entity.getProperty("property:quest");
    
    if (isTired || isHungry || isScared || isQuest) {
        return false;
    }
    
    return true;
}

export function entityDetectNearbyEntities(entity, detectionRadius) {
    const dimension = entity.dimension;

    const mobs = dimension.getEntities({
        location: entity.location,
        maxDistance: detectionRadius
    });

    return mobs;
}

export function entityDetectNearbyMobs(entity, detectionRadius) {
    const dimension = entity.dimension;

    const mobs = dimension.getEntities({
        location: entity.location,
        maxDistance: detectionRadius,
        families: ["mob"]
    });

    return mobs;
}

export function entityDetectNearbyPets(player, minDistance, maxDistance) {
    const dimension = player.dimension;
    const nearbyPets = dimension.getEntities({
        location: player.location,
        minDistance: minDistance,
        maxDistance: maxDistance,
        families: ["pet"]
    });
    return nearbyPets;
}