import * as mc from "@minecraft/server"



// store all data
export function setEntityData(item, entity, player) {
    let healthComponent = entity.getComponent(mc.EntityComponentTypes.Health);
    let currentHealth = healthComponent.currentValue;
    let skinVariant = entity.getProperty("property:skin_variant");
    let currentLevel = entity.getProperty("property:level");
    let xpCurrent = entity.getProperty("property:xp_current");
    let xpRequired = entity.getProperty("property:xp_required");
    let xpMod = entity.getProperty("property:xp_mod");
    let entityData = {
        "entityType": entity.typeId,
        "entityName": entity.nameTag,
        "health": currentHealth,
        "skinVariant": skinVariant,
        "friendshipLevel": currentLevel,
        "xpCurrent": xpCurrent,
        "xpRequired": xpRequired,
        "xpMod": xpMod
    };
    let entityDataString = JSON.stringify(entityData);
    item.setDynamicProperty("cyd_mp_entityData", entityDataString);
}



// get all entity data
export function getEntityData(item) {
    let entityDataString = item.getDynamicProperty("cyd_mp_entityData");
    if (!entityDataString) {
        return null;
    }

    // Parse the JSON string back into an object
    let entityData;
    try {
        entityData = JSON.parse(entityDataString);
    } catch (error) {
        console.error("Failed to parse entity data:", error);
        return null;
    }
    return entityData;
}

export function summonEntity(entityType, entityName, health, skinVariant, friendshipLevel, xpCurrent, xpRequired, xpMod, player) {
    // spawn the entity
    const spawnEntity = player.dimension.spawnEntity(entityType, {
        x: player.location.x,
        y: player.location.y,
        z: player.location.z + 2,
        });
    
    // get components
    let tameComponent = spawnEntity.getComponent(mc.EntityComponentTypes.Tameable);
    let healthComponent = spawnEntity.getComponent(mc.EntityComponentTypes.Health);
    
    // tame the entity
    tameComponent.tame(player);
    
    // set health if it is lower than the default max
    if (health < healthComponent.currentValue) {
        spawnEntity.setCurrentValue(health);
    }
    
    // name the entity if it has a name
    if (entityName !== "") {
        spawnEntity.nameTag = entityName;
    }
    
    // set the properties
    spawnEntity.setProperty("property:skin_variant", skinVariant);
    spawnEntity.setProperty("property:level", friendshipLevel);
    spawnEntity.setProperty("property:xp_current", xpCurrent);
    spawnEntity.setProperty("property:xp_required", xpRequired);
    spawnEntity.setProperty("property:xp_mod", xpMod);

    player.dimension.spawnParticle("cyd_mp:cuteball_impact_1", spawnEntity.location);
    player.dimension.spawnParticle("cyd_mp:cuteball_impact_2", spawnEntity.location);
    player.dimension.spawnParticle("cyd_mp:cuteball_impact_3", spawnEntity.location);
}