import { Entity, Player, system } from "@minecraft/server";
import { EntityProperites } from "../../entities/utils/entityProperties";
import { EntityHelper } from "../../entities/utils/entityHelper";

export const CAMOUFLAGE_POTION = {
    _consumeEffect: EntityHelper.createEntityEffect("invisibility", 0.5, 0, false),
    _potionDuration: (10 * 60) * 20,
    _comouflagePotionItemType: "piki_beyondsurvival:camouflage_potion",

    /**
     * 
     * @param {Player} player 
     */
    onConsume(player) {
        player.setDynamicProperty(EntityProperites.camouflagePotionConsumedStamp, system.currentTick)
    },

    /**
     * 
     * @param {boolean} initialSpawn 
     * @param {Player} player 
     * @returns 
     */
    shouldAdjustPotionDuration(initialSpawn, player) {
        return initialSpawn && player.getDynamicProperty(EntityProperites.camouflagePotionConsumedStamp)
    },

    /**
     * 
     * @param {Player} player 
     */
    adjustPotionDuration(player) {
        const currentTimestamp = player.getDynamicProperty(EntityProperites.camouflagePotionConsumedStamp)
        const leftTimestamp = player.getDynamicProperty(EntityProperites.lastLeaveTimstamp) ?? system.currentTick
        const joinedTimestamp = system.currentTick
        const newTimestamp = currentTimestamp + (joinedTimestamp - leftTimestamp)
        
        player.setDynamicProperty(EntityProperites.camouflagePotionConsumedStamp, newTimestamp)
    },

    /**
     * 
     * @param {Player} player 
     */
    applyConsumeEffect(player) {
        const {effectType, duration, amplifier, showParticles} = this._consumeEffect
        if (player.getEffect(effectType)?.duration > 5) return

        player.addEffect(effectType, duration, {amplifier: amplifier, showParticles: showParticles})
    },

    /**
     * 
     * @param {Player} player 
     */
    isCamouflaging(player) {
        const lastConsumedTime = player.getDynamicProperty(EntityProperites.camouflagePotionConsumedStamp);
        if (!lastConsumedTime) return
        const timeNotExceeded = system.currentTick - lastConsumedTime <= this._potionDuration;
        return timeNotExceeded && player.isSneaking
    },

    equalsItemId(typeId) {
        return typeId == this._comouflagePotionItemType
    }
}