package com.anonymous.Assemblr;

import androidx.annotation.NonNull;

import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReadableArray;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;

public class MyTcpSocketModule extends ReactContextBaseJavaModule {
    public MyTcpSocketModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

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

    @ReactMethod
    public void writeToSocket(String ip, int port, ReadableArray data, Promise promise) {
        try (Socket socket = new Socket(ip, port)) {
            OutputStream output = socket.getOutputStream();
            for (int i = 0; i < data.size(); i++) {
                String item = data.getString(i);
                assert item != null;
                output.write(item.getBytes());
            }
            output.flush();
            promise.resolve("ok");
        } catch (IOException e) {
            promise.reject("ERROR", e.getMessage());
        }
    }
}