/**
 * rData Local-First Client
 *
 * Syncs shared analytics dashboard config across space members.
 */

import { DocumentManager } from '../../shared/local-first/document';
import type { DocumentId } from '../../shared/local-first/document';
import { EncryptedDocStore } from '../../shared/local-first/storage';
import { DocSyncManager } from '../../shared/local-first/sync';
import { DocCrypto } from '../../shared/local-first/crypto';
import { dataSchema, dataDocId } from './schemas';
import type { DataDoc, TrackedApp } from './schemas';

export class DataLocalFirstClient {
	#space: string;
	#documents: DocumentManager;
	#store: EncryptedDocStore;
	#sync: DocSyncManager;
	#initialized = false;

	constructor(space: string, docCrypto?: DocCrypto) {
		this.#space = space;
		this.#documents = new DocumentManager();
		this.#store = new EncryptedDocStore(space, docCrypto);
		this.#sync = new DocSyncManager({ documents: this.#documents, store: this.#store });
		this.#documents.registerSchema(dataSchema);
	}

	get isConnected(): boolean { return this.#sync.isConnected; }

	async init(): Promise<void> {
		if (this.#initialized) return;
		await this.#store.open();
		const cachedIds = await this.#store.listByModule('data', 'config');
		const cached = await this.#store.loadMany(cachedIds);
		for (const [docId, binary] of cached) this.#documents.open<DataDoc>(docId, dataSchema, binary);
		await this.#sync.preloadSyncStates(cachedIds);
		const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
		const wsUrl = `${proto}//${location.host}/ws/${this.#space}`;
		try { await this.#sync.connect(wsUrl, this.#space); } catch { console.warn('[DataClient] Working offline'); }
		this.#initialized = true;
	}

	async subscribe(): Promise<DataDoc | null> {
		const docId = dataDocId(this.#space) as DocumentId;
		let doc = this.#documents.get<DataDoc>(docId);
		if (!doc) {
			const binary = await this.#store.load(docId);
			doc = binary
				? this.#documents.open<DataDoc>(docId, dataSchema, binary)
				: this.#documents.open<DataDoc>(docId, dataSchema);
		}
		await this.#sync.subscribe([docId]);
		return doc ?? null;
	}

	getDoc(): DataDoc | undefined { return this.#documents.get<DataDoc>(dataDocId(this.#space) as DocumentId); }
	onChange(cb: (doc: DataDoc) => void): () => void { return this.#sync.onChange(dataDocId(this.#space) as DocumentId, cb as (doc: any) => void); }

	addTrackedApp(app: TrackedApp): void {
		const docId = dataDocId(this.#space) as DocumentId;
		this.#sync.change<DataDoc>(docId, `Track ${app.name}`, (d) => { d.trackedApps[app.id] = app; });
	}

	removeTrackedApp(appId: string): void {
		const docId = dataDocId(this.#space) as DocumentId;
		this.#sync.change<DataDoc>(docId, `Untrack app`, (d) => { delete d.trackedApps[appId]; });
	}

	async disconnect(): Promise<void> { await this.#sync.flush(); this.#sync.disconnect(); }
}
