import type { ExcalidrawElement } from "@excalidraw/excalidraw/element/types"
import { generateNKeysBetween } from "fractional-indexing"
import * as Y from "yjs"

/** Seed y-excalidraw Y.Array from parsed file elements when no yjsState exists yet. */
export function seedYExcalidrawElements(
  ydoc: Y.Doc,
  elements: readonly ExcalidrawElement[],
  files: Record<string, unknown>
): void {
  const yElements = ydoc.getArray<Y.Map<unknown>>("elements")
  const yAssets = ydoc.getMap("assets")
  if (yElements.length > 0) return

  ydoc.transact(() => {
    if (elements.length > 0) {
      const keys = generateNKeysBetween(null, null, elements.length)
      for (let i = 0; i < elements.length; i++) {
        yElements.push([
          new Y.Map(
            Object.entries({
              pos: keys[i],
              el: { ...elements[i] },
            })
          ),
        ])
      }
    }
    for (const [id, asset] of Object.entries(files)) {
      yAssets.set(id, asset)
    }
  })
}
