import ws from 'ws';

process.env["NODE_TLS_REJECT_UNAUTHORIZED"]="0"
// const ADDR = "ws://112.74.39.99:8080/ws"
const ADDR = "ws://47.117.75.243:8080/ws"

export function makeClient(
  onMessage: ((data: ws.RawData) => void) | any = undefined,
) : Promise<ws.WebSocket> {
  return new Promise((resolve, reject) => {
    let client = new ws.WebSocket(ADDR, {headers: {
      ["X-Api-Key"]: "simpletest2025_001",
    }}) 

    client.on('message', (data)=>{
      if (onMessage != undefined) {
        onMessage(data)
      } else {
        console.log("agent -> me:")
        console.log(data.toString())
      }
    })

    client.on('error', console.error)
    client.on('open', ()=>{
      console.log('connected')
      resolve(client)
    })
    client.on('close', ()=>{
      console.log('disconnected')
    })
  })
}

export function sleep(ms: number) : Promise<any> {
  return new Promise( resolve => setTimeout(resolve, ms))
}