using NetMQ;
using NetMQ.Sockets;

namespace Hawkeye.VisionBuilder.Workflow.DataTransfer;

public class CSharpDataTransferMQ
{
    
    private object _syncObject = new object();
    private readonly ResponseSocket _server;

    public CSharpDataTransferMQ()
    {
        this._server = new ResponseSocket();
        _server.Bind("tcp://*:5555");
        
    }

    public byte[] TransferData(string command, byte mode, byte[] data)
    {
        lock (_syncObject)
        {
            return TransferDataInternal(command,mode,data);
        }

    }

    private byte[] TransferDataInternal(string command,byte mode,byte[] data)
    {
        Console.WriteLine("Waiting for request");
        _server.ReceiveFrameBytes();

        MemoryStream ms = new MemoryStream();
        BinaryWriter bw = new BinaryWriter(ms);
        var functionBytes=System.Text.Encoding.ASCII.GetBytes(command);
        bw.Write(functionBytes.Length);
        bw.Write(functionBytes);
        bw.Write(mode);
        bw.Write(data);

        


        
        Console.WriteLine("Sending response");
        _server.SendFrame(ms.ToArray());

        Console.WriteLine("Waiting for request");
        var result= _server.ReceiveFrameBytes();

        _server.SendFrame("OK");
        
        return result;
    }
}