/**
 * rTube Local-First Client
 *
 * Syncs shared playlists and watch party state.
 */

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 { tubeSchema, tubeDocId } from './schemas';
import type { TubeDoc, Playlist, PlaylistEntry } from './schemas';

export class TubeLocalFirstClient {
	#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(tubeSchema);
	}

	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('tube', 'playlists');
		const cached = await this.#store.loadMany(cachedIds);
		for (const [docId, binary] of cached) this.#documents.open<TubeDoc>(docId, tubeSchema, 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('[TubeClient] Working offline'); }
		this.#initialized = true;
	}

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

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

	savePlaylist(playlist: Playlist): void {
		const docId = tubeDocId(this.#space) as DocumentId;
		this.#sync.change<TubeDoc>(docId, `Save playlist ${playlist.name}`, (d) => { d.playlists[playlist.id] = playlist; });
	}

	deletePlaylist(playlistId: string): void {
		const docId = tubeDocId(this.#space) as DocumentId;
		this.#sync.change<TubeDoc>(docId, `Delete playlist`, (d) => { delete d.playlists[playlistId]; });
	}

	addToPlaylist(playlistId: string, entry: PlaylistEntry): void {
		const docId = tubeDocId(this.#space) as DocumentId;
		this.#sync.change<TubeDoc>(docId, `Add to playlist`, (d) => {
			if (d.playlists[playlistId]) d.playlists[playlistId].entries.push(entry);
		});
	}

	startWatchParty(videoName: string, startedBy: string | null): void {
		const docId = tubeDocId(this.#space) as DocumentId;
		this.#sync.change<TubeDoc>(docId, `Start watch party`, (d) => {
			d.watchParty = { videoName, startedBy, startedAt: Date.now(), position: 0, playing: true };
		});
	}

	updateWatchPartyPosition(position: number, playing: boolean): void {
		const docId = tubeDocId(this.#space) as DocumentId;
		this.#sync.change<TubeDoc>(docId, `Sync playback`, (d) => {
			if (d.watchParty) { d.watchParty.position = position; d.watchParty.playing = playing; }
		});
	}

	endWatchParty(): void {
		const docId = tubeDocId(this.#space) as DocumentId;
		this.#sync.change<TubeDoc>(docId, `End watch party`, (d) => { d.watchParty = null; });
	}

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