import ws from 'ws';

process.env["NODE_TLS_REJECT_UNAUTHORIZED"]="0"
// const ADDR = "ws://127.0.0.1:8080/ws?api_key=simpletest2025_001"
const ADDR = "ws://47.117.75.243:8080/ws?api_key=simpletest2025_001"

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",
    // }}) 
    let client = new ws.WebSocket(ADDR) 

    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))
}