import { fromUint8Array, toUint8Array } from '../../common'; import { AspectStateApi } from '../../hostapi'; import { ImmutableAspectValue, MutableAspectValue } from './aspect-state-interface'; const stateApi = AspectStateApi.instance(); export class MutableAspectState { private static _instance: MutableAspectState | null; private constructor() {} public get(key: string): MutableStateValue { return new MutableStateValue(key); } public static instance(): MutableAspectState { if (!this._instance) { this._instance = new MutableAspectState(); } return this._instance!; } } export class ImmutableAspectState { private static _instance: ImmutableAspectState | null; private constructor() {} public get(key: string): ImmutableStateValue { return new ImmutableStateValue(key); } public static instance(): ImmutableAspectState { if (!this._instance) { this._instance = new ImmutableAspectState(); } return this._instance!; } } export class ImmutableStateValue implements ImmutableAspectValue { protected val: T; protected loaded: boolean = false; constructor(protected readonly key: string) { this.val = fromUint8Array(new Uint8Array(0)); } reload(): void { this.val = fromUint8Array(stateApi.get(this.key)); this.loaded = true; } unwrap(): T { if (!this.loaded) { this.reload(); } return this.val; } } export class MutableStateValue extends ImmutableStateValue implements MutableAspectValue { set(value: T): void { stateApi.set(this.key, toUint8Array(value)); this.loaded = false; } }