package com.vsu.fcounter.udpbroadcast;

import androidx.annotation.NonNull;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UdpBroadcastModule extends ReactContextBaseJavaModule {

    ReactContext reactContext;
    private int port = 5555; // 远程端口
    private int localPort = 5556; // 本地接收端口
    private int timeout = 500; // 接收数据超时时间
    private String serverIP = "255.255.255.255"; // 广播地址

    UdpBroadcastModule(ReactApplicationContext reactContext) {
        super(reactContext);
        this.reactContext = reactContext;
    }

    @NonNull
    @Override
    public String getName() {
        return "UdpBroadcast";
    }

    @ReactMethod
    void send(ReadableMap params, Promise promise){
        int localPort = this.localPort;
        if (params.hasKey("localPort"))
            localPort = params.getInt("localPort");
        WritableArray res = Arguments.createArray();
        try (DatagramSocket ds = new DatagramSocket(localPort)) {
            String data = params.getString("data");
            if (data == null) {
                promise.resolve(false);
                return;
            }
            int port = this.port;
            if (params.hasKey("port"))
                port = params.getInt("port");
            int timeout = this.timeout;
            if (params.hasKey("timeout"))
                port = params.getInt("timeout");
            String serverIP = this.serverIP;
            if (params.hasKey("serverIP"))
                serverIP = params.getString("serverIP");
            InetAddress server = InetAddress.getByName(serverIP);
            DatagramPacket dp = new DatagramPacket(data.getBytes(), data.getBytes().length, server, port);
            ds.send(dp);
            byte[] message = new byte[1024];
            dp = new DatagramPacket(message, message.length);
            ds.setSoTimeout(timeout);
            long begin = System.currentTimeMillis();
            while (System.currentTimeMillis() - begin < timeout) {
                ds.receive(dp);
                WritableMap ret = Arguments.createMap();
                ret.putInt("port", dp.getPort());
                ret.putString("ip", dp.getAddress().getHostAddress());
                ret.putString("data", new String(dp.getData()));
                res.pushMap(ret);
            }
            promise.resolve(res);
        } catch (IOException e) {
            e.printStackTrace();
            promise.resolve(res);
        }
    }

}
