import { type RNGState, SeededRandom } from "@common/random";
import { Component, World } from "../core/world";
import { component } from "../utils/decorators";

@component
export class Random extends Component<{ random: RNGState }> {
    private rng?: SeededRandom;

    constructor(random: SeededRandom | string | number | RNGState = Date.now()) {
        super({
            random: (() => {
                this.rng = random instanceof SeededRandom ? random : new SeededRandom(random);
                return this.rng.getState();
            })()
        });
    }

    use<T>(fn: (rng: SeededRandom) => T): T {
        if (this.rng) {
            this.rng.setState(this.state.random);
        } else {
            this.rng = new SeededRandom(this.state.random);
        }
        const result = fn(this.rng);
        this.state.random = this.rng.getState();
        return result;
    }
}

export const getWorldRandom = (world: World): Random => {
    const random = world.findComponent(Random);
    if (random) {
        return random;
    }

    const entity = world.createEntity('random_*');
    return entity.add(new Random());
}
