package com.tomas.ht_ydt.lib.common;

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

import com.tomas.ht_ydt.R;
import com.tomas.ht_ydt.lib.TcpClient;


public abstract class AsyncTcpClient extends AsyncTask<String, String, TcpClient> {

    TcpClient mTcpClient;

    Context context;
    String SERVER_IP;
    int SERVER_PORT;
    String message;

    StringBuffer stringBuffer = new StringBuffer();

    abstract protected void onFinished(String response);

    public AsyncTcpClient(Context context, String SERVER_IP, int SERVER_PORT, String message) {
        this.context = context;
        this.SERVER_IP = SERVER_IP;
        this.SERVER_PORT = SERVER_PORT;
        this.message = message;
    }

    @Override
    protected void onPostExecute(TcpClient unused) {
        super.onPostExecute(unused);
    }

    @Override
    protected TcpClient doInBackground(String... message) {

        //we create a TCPClient object
        mTcpClient = new TcpClient(SERVER_IP, SERVER_PORT, context
                , this.message
                , new TcpClient.OnMessageReceived() {
                    @Override
                    //here the messageReceived method is implemented
                    public void messageReceived(String message) {
                        //this method calls the onProgressUpdate
                        publishProgress(message);

                    }
                }
        );


        mTcpClient.start();




        // Sending message...
        //mTcpClient.sendMessage(this.message);
        //mTcpClient.stopClient();

        return null;
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        //response received from server
        Log.d(context.getString(R.string.tag), "response " + values[0]);
        //process server response here....
        stringBuffer.append(values[0]);

        //mTcpClient.stopClient();
        onFinished(stringBuffer.toString());

        mTcpClient.stopClient();
    }
}
