import { system, world } from "@minecraft/server";
import * as utils from "./utils"
import * as inventory_utils from "./inventory_utils"

let tickCount = 0;
export async function onTick() {
    
    tickCount++;
    if (tickCount < 20) return;
    tickCount = 0;

    for (let player of await world.getAllPlayers()){
        if (player === undefined)
            continue;
        //if (inventory_utils.isHoldingPhone(player) && player.hasTag("goe_spa_flashlight_mode"))
        //    drain(player, 2);
        //else 
        if(inventory_utils.isHoldingOpenPhone(player))
            drain(player, 1);
        else if(player.hasTag("goe_spa_satellite_mode"))
        {
            let satelliteDrain = player.getDynamicProperty("goe_spa_satellite_drain");
            satelliteDrain = satelliteDrain ? satelliteDrain + 1 : 1;
            player.setDynamicProperty("goe_spa_satellite_drain", satelliteDrain);
        }

        inventory_utils.replaceChargedPhone(player);
    }
}

export function drainAfterSatellite(player){
    let satelliteDrain = player.getDynamicProperty("goe_spa_satellite_drain");
    satelliteDrain = satelliteDrain ? satelliteDrain : 0;
    drain(player, satelliteDrain);
    player.setDynamicProperty("goe_spa_satellite_drain", undefined);
}
export function drain(player, amount) {
    if (amount <= 0)
    {
        utils.debug("attempt to drain negative amount: "+amount);
        return false;
    }
    
    if (inventory_utils.isHoldingOpenPhone(player) || (inventory_utils.isHoldingPhone(player) && player.hasTag("goe_spa_flashlight_mode")))
    {
        inventory_utils.drainPhone(player, amount);
        return true;
    }
    
    utils.debug("attempt to drain bettery while player is not holding phone: ");
    return false;
    
    inventory_utils.drainPhone(player, amount);
}

export function getChargePercentage(player) {
    if (!inventory_utils.isHoldingPhone(player))
        return 0;
    let phoneItem = inventory_utils.getItemInHand(player);
    let durability = getCharge(player);
	let maxDurability = phoneItem.getComponent("durability").maxDurability;
    return Math.ceil((durability/maxDurability) * 100);
}

export function getCharge(player)
{
    if (!inventory_utils.isHoldingPhone(player))
        return 0;
    let phoneItem = inventory_utils.getItemInHand(player);
    return phoneItem.getComponent("durability").maxDurability - phoneItem.getComponent("durability").damage;
}

export function canAfford(player, amount)
{
    return getCharge(player) >= amount;
}
