/*************************************************************
 * By: Coralys Cubero Rivera
 * Date: 2019
 *************************************************************/

package uprrp.tania;

import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class SendAnswersToServer extends AsyncTask <String, String, String> {
    @Override
    protected String doInBackground(String... strings) {
        String jsonSurveyAnswers  = " ";
        try {
            jsonSurveyAnswers = URLEncoder.encode("data", "UTF-8") + "=" + URLEncoder.encode(strings[0], "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String serverReply = "";
        BufferedReader serverReader;

        //Send data
        try
        {
            //Defined URL  where to send data
            URL url = new URL("https://tania.uprrp.edu/parseAnswers.php");

            // Send POST data request
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(jsonSurveyAnswers);
            wr.flush();

            // Get the server response
            serverReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder serverResponse = new StringBuilder();
            String serverResponseLine;

            // Read Server Response
            while((serverResponseLine = serverReader.readLine()) != null)
            {
                // Append server response in string
                serverResponse.append(serverResponseLine);
            }

            serverReply = serverResponse.toString();
        }
        catch(Exception ex) {
            Log.e("ERROR SURVEYS ANSWERS", ex.getMessage());
        }

        return serverReply;
    }

    @Override
    protected void onPostExecute(String s) {
        Log.d("SURVEYS ANSWERS REPLY", s);

    }

}
