package com.example.lfrmobileapp;

import android.os.AsyncTask;
import android.util.Log;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

public class DataTransferAsyncTask extends AsyncTask<Void, Void, Void> {
    private static final int sendRatePerSecond = 4;
    private String ipAdress;
    private int portNumber;
    private String telegram;
    private boolean connected;

    public DataTransferAsyncTask(String ipAdress, int portNumber) {
        this.ipAdress = ipAdress;
        this.portNumber = portNumber;
        this.telegram = "";
        this.connected = false;
    }

    public void writeTelegram(String telegram) {
        this.telegram = telegram;
    }

    @Override
    protected Void doInBackground(Void... params) {
        while(!isCancelled()) {
            try {
                Socket socket = new Socket(ipAdress, portNumber);
                DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
                connected = true;
                while (!isCancelled() && telegram.length() > 0) {
                    Log.v("TAG", telegram + "\n");
                    outputStream.writeBytes(telegram);
                    outputStream.flush();
                    Thread.sleep(1000 / sendRatePerSecond);
                }
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
                connected = false;
            }
        }
        return null;
    }


    public boolean getConnectionState(){
        return connected;
    }
}
