import { world, system } from "@minecraft/server";
import { fo } from "./utilities/fo_constants";



export function initPlayerPatterns() {
    
    const BED_USAGE_PROPERTY = "bed_usage_data";
    const BASE_LOCATION_PROPERTY = "base_location";
    const REQUIRED_USES = 12,
        bedUsageCooldownMap = new Map(); 


    
    function hasBaseLocation() {
        return world.getDynamicProperty(BASE_LOCATION_PROPERTY) !== undefined;
    }

    
    function getBedUsageData() {
        if (hasBaseLocation()) return {}; 
        const data = world.getDynamicProperty(BED_USAGE_PROPERTY);
        return data ? JSON.parse(data) : {};
    }

    
    function saveBedUsageData(data) {
        if (hasBaseLocation()) return; 
        world.setDynamicProperty(BED_USAGE_PROPERTY, JSON.stringify(data));
    }

    
    function getLocationKey(location) {
        return `${location.x},${location.y},${location.z},${location.dimensionId}`;
    }

    
    world.afterEvents.playerInteractWithBlock.subscribe((event) => {
        
        if (hasBaseLocation()) return;

        const block = event.block;
        const player = event.player;

        
        if (block.typeId.includes("bed") && !bedUsageCooldownMap.get(player.id)) {
            const bedLocation = {
                x: block.x,
                y: block.y,
                z: block.z,
                dimensionId: player.dimension.id
            };

            
            bedUsageCooldownMap.set(player.id, true);

            system.runTimeout(() => {
                bedUsageCooldownMap.set(player.id, false);
            }, 1200); 

            const locationKey = getLocationKey(bedLocation);
            const bedUsageData = getBedUsageData();

            
            bedUsageData[locationKey] = (bedUsageData[locationKey] || 0) + 1;

            

            
            saveBedUsageData(bedUsageData);

            
            if (bedUsageData[locationKey] >= REQUIRED_USES) {
                
                world.setDynamicProperty(BASE_LOCATION_PROPERTY, JSON.stringify(bedLocation));

                
                world.setDynamicProperty(BED_USAGE_PROPERTY, undefined);

                
            }
        }
    });

}


export function getBaseLocation() {
    const data = world.getDynamicProperty(BASE_LOCATION_PROPERTY);
    return data ? JSON.parse(data) : null;
}


export function resetBaseSystem() {
    world.setDynamicProperty(BASE_LOCATION_PROPERTY, undefined);
    world.setDynamicProperty(BED_USAGE_PROPERTY, undefined);
}
