import { VideoWS } from '../ws.ts';
import net from 'net';
import path from 'path';
import fs from 'fs';

// const videoTestPath = path.join(process.cwd(), 'videos/asr_example.wav');
// const videoTestPath = path.join(process.cwd(), 'videos/asr_example2.wav');
// const videoTestPath = path.join(process.cwd(), 'videos/tts_mix.mp3');
const videoTestPath = path.join(process.cwd(), 'videos/my_speech_text.wav');
const videoTestPath3 = path.join(process.cwd(), 'funasr_test.wav');
const name = 'output-1746007775571.mp3';
const videoTestPath2 = path.join(process.cwd(), 'build', name);

const url = 'wss://funasr.xiongxiao.me';
const url5 = 'https://1.15.101.247:10095'; // pro
// const ws = new VideoWS({
//   // url: 'wss://192.168.31.220:10095',
//   url: 'wss://funasr.xiongxiao.me',
//   isFile: true,
//   // mode: 'offline',
//   wav_format: 'mp3',
//   onConnect: async () => {
//     console.log('onConnect');
//     const data = fs.readFileSync(videoTestPath);
//     let sampleBuf = new Uint8Array(data);

//     var chunk_size = 960; // for asr chunk_size [5, 10, 5]
//     let totalsend = 0;
//     let len = 0;
//     ws.start();
//     while (sampleBuf.length >= chunk_size) {
//       const sendBuf = sampleBuf.slice(0, chunk_size);
//       totalsend = totalsend + sampleBuf.length;
//       sampleBuf = sampleBuf.slice(chunk_size, sampleBuf.length);
//       if (len === 100) {
//         // ws.stop();
//         // ws.start();
//         // await new Promise((resolve) => setTimeout(resolve, 1000));
//       }

//       await new Promise((resolve) => setTimeout(resolve, 10));
//       ws.send(sendBuf);
//       len++;
//     }
//     await new Promise((resolve) => setTimeout(resolve, 1000));
//     ws.stop();
//     console.log('len', len);
//   },
// });

// const server = net.createServer((socket) => {
//   socket.on('data', (data) => {
//     console.log('data', data);
//   });
// });
// server.listen(10096);

const ws2 = new VideoWS({
  url: url5,
  mode: '2pass',
  onConnect: async () => {
    const data = fs.readFileSync(videoTestPath3);
    // await ws2.sendBuffer(data, { wav_format: 'mp3' });
    // await new Promise((resolve) => setTimeout(resolve, 1000));
    // const data2 = fs.readFileSync(videoTestPath2);
    // await ws2.sendBuffer(data2, { wav_format: 'mp3' });
    ws2.emitter.on('message', (event) => {
      console.log('message', event.data);
    });
    ws2.emitter.on('result', (result) => {
      if (result.is_final) {
        console.log('Final result:', result);
        process.exit(0);
      }
    });
    await ws2.start();
    await ws2.sendBuffer(data, { online: true });
    setTimeout(() => {
      ws2.stop();
    }, 4000);
  },
});
