import { NavigationState } from "./navigation_state.mjs"

//TODO: do we need a parent() function?
//TODO: implement orders
//TODO: make persistent() return scoped localStorage

// we only use this in the public API, not internally, as all the components have separate lifetimes anyway
export class ApplicationState {

	#parent
	#address
	#navigation
	#remote
	#orders
	#cache

	constructor(parent, address, navigation, remote, orders, cache) {
		this.#parent = parent
		this.#address = address
		this.#navigation = navigation
		this.#remote = remote
		this.#orders = orders
		this.#cache = cache
		Object.freeze(this)
	}

	scope(address) {
		return new ApplicationState(this, this.#address.concat([address].flat()), this.#navigation, this.#remote, null, this.#cache)
	}

	get navigation() {
		if (this.#navigation instanceof NavigationState) {
			return this.#navigation.scope(this.#address)
		} else {
			return this.#navigation
		}
	}

	get cache() {
		return this.#address.reduce((current, key) => ((typeof current[key] !== 'object' || current[key] == null || Array.isArray(current[key])) ? (current[key] = {}) : current[key]), this.#cache)
	}

	observe(fn) {
		this.#remote.observe(this.#address, fn)
	}

	get remote() {
		return this.#remote.results(this.#address)
	}

	get persistent() {
		throw "Not yet implemented"
	}

	order() {
		throw "Not yet implemented"
	}

	get orders() {
		throw "Not yet implemented"
	}

}
