import * as Y from 'yjs'

declare const require: any

let doc: Y.Doc | null = null
let provider: any | null = null

export const initCRDT = (roomName: string, signalingUrl: string) => {
  doc = new Y.Doc()
  
  provider = new (require('y-webrtc').WebrtcProvider)(
    roomName,
    doc,
    {
      signaling: [signalingUrl],
    }
  )

  provider.on('status', (status: string) => {
    console.log('[CRDT] Status:', status)
  })

  return doc
}

export const getCRDTDoc = (): Y.Doc | null => {
  return doc
}

export const getCRDTProvider = () => {
  return provider
}

export const destroyCRDT = () => {
  provider?.destroy()
  doc?.destroy()
  doc = null
  provider = null
}