package com.yeejoin.amos.boot.module.jcs.biz.audioToText;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.*;
import java.util.concurrent.TimeUnit;

import static com.yeejoin.amos.boot.module.jcs.biz.audioToText.util.SpeechTranscriberDemo.getSleepDelta;

/**
 * 模拟客户端发送数据
 */
@Component
public class SocketClient {
    private static final Logger logger = LoggerFactory.getLogger(SocketClient.class);
    private static final String[] testFilePath = {
            "C:\\Users\\DELL\\Desktop\\yuyin\\out1.pcm",
            "C:\\Users\\DELL\\Desktop\\yuyin\\out.pcm",
    };

    public static void main(String[] args) throws SocketException {
        SocketClient socketClient = new SocketClient();
        socketClient.processUdp(25002, 1);
    }

    @Async
    public void processUdp(int port, int type) throws SocketException {
        if (type < 0) type = 0;
        if (type >= testFilePath.length) type -= 1;

        try (DatagramSocket datagramSocket = new DatagramSocket();
             FileInputStream fis = new FileInputStream(new File("C:\\Users\\DELL\\Desktop\\ffmpeg-4.4-full_build-shared\\bin\\out.pcm"));) {
            byte[] b = new byte[1280];
            int len;
            while ((len = fis.read(b)) > 0) {
                String logs= String.format("send data pack length: %s",len);

                logger.error( logs);

                datagramSocket.send(new DatagramPacket(b, b.length,InetAddress.getLocalHost(), port));
                int deltaSleep = getSleepDelta(len, 16000);
                Thread.sleep(deltaSleep);
                TimeUnit.MILLISECONDS.sleep(100);
            }
            datagramSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Async
    public void processTcp(int port, int type) {
        if (type < 0) type = 0;
        if (type >= testFilePath.length) type -= 1;

        try (Socket socket = new Socket();
             FileInputStream fis = new FileInputStream(new File(testFilePath[type]));) {
            socket.connect(new InetSocketAddress(InetAddress.getLocalHost().getHostAddress(), port));
            OutputStream outputStream = socket.getOutputStream();
            byte[] b = new byte[4096];
            int len;
            while ((len = fis.read(b)) > 0) {


                String logs= String.format("send data pack length: %s",len);

                logger.error( logs);
                outputStream.write(b);
                TimeUnit.MILLISECONDS.sleep(200);
            }
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

