import ObservableStorageObserver from "/emcJS/util/observer/data/storage/ObservableStorageObserver.js";
import Savestate from "/GameTrackerJS/savestate/Savestate.js";
import LocationStateManager from "/GameTrackerJS/statemanager/world/location/LocationStateManager.js";
import DefaultAPLocationState from "./DefaultAPLocationState.js";
import "../../../util/registerStorages.js";

const STORAGES = {
    gossipstoneItems: Savestate.getStorage("gossipstoneItems"),
    gossipstoneLocations: Savestate.getStorage("gossipstoneLocations")
};

const LOCATION = new WeakMap();
const ITEM = new WeakMap();

export default class GossipstoneState extends DefaultAPLocationState {

    constructor(ref, props) {
        super(ref, props);

        /* VALUES */
        const gossipstoneItemsObserver = new ObservableStorageObserver(STORAGES.gossipstoneItems, ref);
        ITEM.set(this, gossipstoneItemsObserver.value);
        gossipstoneItemsObserver.onChange((event) => {
            this.item = event.value;
        });

        const gossipstoneLocationsObserver = new ObservableStorageObserver(STORAGES.gossipstoneLocations, ref);
        LOCATION.set(this, gossipstoneLocationsObserver.value);
        gossipstoneLocationsObserver.onChange((event) => {
            this.location = event.value;
        });
    }

    set item(value) {
        const ref = this.ref;
        if (typeof value != "string") {
            value = "";
        }
        const oldValue = this.item;
        if (value != oldValue) {
            ITEM.set(this, value);
            STORAGES.gossipstoneItems.set(ref, value);
            // external
            const event = new Event("item");
            event.value = value;
            this.dispatchEvent(event);
        }
    }

    get item() {
        return ITEM.get(this);
    }

    set location(value) {
        const ref = this.ref;
        if (typeof value != "string") {
            value = "";
        }
        const oldValue = this.location;
        if (value != oldValue) {
            LOCATION.set(this, value);
            STORAGES.gossipstoneLocations.set(ref, value);
            // external
            const event = new Event("location");
            event.value = value;
            this.dispatchEvent(event);
        }
    }

    get location() {
        return LOCATION.get(this);
    }

}

LocationStateManager.register("gossipstone", GossipstoneState);
