import { AwaitStore } from "@hibas123/utils";
import Client, { type ICollectionRef } from "@rtdb2/sdk";
import { readable } from "svelte/store";

const client = new Client(
   "https://rtdb.hibas123.de",
   "screen_share",
   "screen_share"
);

(window as any).db = client;

export const Sessions = client.collection<ISession>("sessions");

export interface ISession {}

export interface IMember {
   lastActive: number;
   offline: boolean;
   name: string;
}

export interface IMessage {
   sender: string;
   message: string;
}

export function collectionToStore<T>(coll: ICollectionRef<T>) {
   return readable<(T & { $id: string })[]>([], (set) => {
      const cancel = new AwaitStore(false);
      (async () => {
         const itr = await coll.onSnapshot();
         cancel.awaitValue(true).then(() => itr.close());
         for await (const snapshot of itr) {
            set(snapshot.docs.map((doc) => ({ ...doc.data(), $id: doc.id })));
         }
      })();

      return () => {
         cancel.send(true);
      };
   });
}
