import State from "./state";

export default class Item {
    constructor() {
        this.id = "item";
        this.name = "An item";
        this.description = "You see nothing special about this item";
        this.type = "item";
        this.state = new State();
        this.usable = true;
        this.takeable = true;
        this.useCallback = null;
        this.takeCallback = null;
        this.dropCallback = null;
        this.tickCallback = null;
        this.context = null;
        this.dynamic = false;
        this.dynamicID = null;
    }

    async onUse() {
        if (this.useCallback) return this.useCallback(this.context);
    }

    async onTake() {
        if (this.takeCallback) return this.takeCallback(this.context);
    }

    async onDrop() {
        if (this.dropCallback) return this.dropCallback(this.context);
    }
    async onTick() {
        if (this.tickCallback) return this.tickCallback(this.context);
    }

    addUseCallback(callback) {
        this.useCallback = callback.bind(this);
    }

    addTakeCallback(callback) {
        this.takeCallback = callback.bind(this);
    }

    addDropCallback(callback) {
        this.dropCallback = callback.bind(this);
    }

    addTickCallback(callback) {
        this.tickCallback = callback.bind(this);
    }

    setState(key, value) {
        return this.state.set(key, value);
    }

    getState(key) {
        return this.state.get(key);
    }

    clone() {
        const clonedItem = new Item();
        clonedItem.id = this.id;
        clonedItem.name = this.name;
        clonedItem.description = this.description;
        clonedItem.type = this.type;
        clonedItem.state = new State();
        clonedItem.usable = this.usable;
        clonedItem.takeable = this.takeable;
        if (this.useCallback) clonedItem.useCallback = this.useCallback.bind(clonedItem);
        if (this.takeCallback) clonedItem.takeCallback = this.takeCallback.bind(clonedItem);
        if (this.dropCallback) clonedItem.dropCallback = this.dropCallback.bind(clonedItem);
        if (this.tickCallback) clonedItem.tickCallback = this.tickCallback.bind(clonedItem);
        clonedItem.context = this.context;
        clonedItem.dynamic = true;
        clonedItem.dynamicID = generateUniqueID();
        this.context.items.push(clonedItem);
        return clonedItem;
    }

    getID() {
        return this.dynamic ? this.dynamicID : this.id;
    }
}

function generateUniqueID() {
    return `dynamic_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}