const {Server} =require("socket.io")
const consola = require("consola")
const _ = require("lodash")
const {v4} =require("uuid")
const {database} = require('../mongo-connector')
const options = {
    collection:null,
    pipelineStream:[],
  
}

function setSocket(config){
const io = new Server(config.server,{
})
config.state.io =  io
io.on("connection",(socket)=>{

   // console.log("Hey",socket)
    config.state.socket = socket
        socket.on("realtime:collection",(options=options,clb)=>{
           
         var uid = v4()
         options._uid= uid
         
         clb({
            ...options,
          
         })

    
        if(options.collection && uid){
            socket.join(uid)
            database.collection(options.collection).watch(options.pipelineStream).on("change",(ev)=>{
                let stream = ev
                stream = _.omit(ev,['ns','_id','lsid','tx'])
                io.to(uid).emit(uid,
                 stream
                    )
            })
        }

    })

    
})
//console.info("Socket are initialized")
}


function subscribeRealTimeCollections(config,model=null,data=null,action=null){
    config?.state?.io?.emit(`collections ${model} ${action}`,{
        model:model,
        action:action,
        data:data
    })

    config?.state?.io?.emit(`collections ${model} *`,{
        model:model,
        action:action,
        data:data
    })

    



}


module.exports = {
    setSocket,
    subscribeRealTimeCollections
}