package uprrp.tania.networking;

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

import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;

import javax.net.ssl.HttpsURLConnection;

import uprrp.tania.URLEventListener;
import uprrp.tania.models.AnsweredAssessmentModel;

public class SendAnswers extends AsyncTask<AnsweredAssessmentModel, Void, String> {

    private static final String TAG = "SendAnswers";
    private static final String sendAnswersURL = "https://tania.uprrp.edu/parseAnswers.php";
    private final URLEventListener myCallback;

    public SendAnswers(URLEventListener callback) {
        this.myCallback = callback;
    }

    // TODO: instead of making a normal POST request with
    //  the body data=<uglyJSON>, we should just send the JSON itself
    //  This is adding unnecessary layers of complexity when decoding AND encoding
    /*
        uglyJSON Format:
        {
            "os": "Android",
            "data": String (containing escaped serializedAssessmentJSON)
        }

        serializedAssessmentJSON Format:
        {
            "id_subquestionnair": String,
            "token": String,
            "preguntas": [
                {
                    "id_question": String,
                    "start_datetime": String,
                    "question_answer": String,
                    "end_datetime": String
                },
                ...
            ]
        }

        WE SHOULD BE INSTEAD SENDING SOMETHING LIKE:
        {
            "os": "Android",
            "token" String,
            "data": {
                "id_subquestionnair": String,
                "preguntas": [
                    {
                        "id_question": String,
                        "start_datetime": String,
                        "question_answer": String,
                        "end_datetime": String
                    },
                    ...
                ]
            }
        }
     */
    @Override
    protected String doInBackground(AnsweredAssessmentModel... answeredAssessments) {

        AnsweredAssessmentModel answeredAssessment = answeredAssessments[0]; // array will only ever contain a single element

        try {

            // Serialize answered assessment
            GsonBuilder builder = new GsonBuilder();
//            builder.setPrettyPrinting(); // the server doesn't like pretty printing...
            String serializedAssessment = builder.create().toJson(answeredAssessment);
            Log.d(TAG,"reconstructedJSON:\n" + serializedAssessment); // log

            // Create wrapper json (a.k.a. uglyJSON)
            JSONObject surveyResults = new JSONObject();
            surveyResults.put("os", "Android");
            surveyResults.put("data", serializedAssessment);

            // Encode data
            String encodedRequestBody = URLEncoder.encode("data", "UTF-8") + "=" + URLEncoder.encode(surveyResults.toString(), "UTF-8");

            // Send POST data request
            URL url = new URL(sendAnswersURL);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(encodedRequestBody);
            wr.flush();

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

            String line = "";
            while(line != null) {
                serverResponse.append(line);
                line = serverReader.readLine();
            }

            String response = serverResponse.toString();
            Log.d(TAG, "The server's response is: " + response);
            if(response.startsWith("Success")) {
                return response;
            } else {
                return null;
            }


        } catch (JsonSyntaxException e) {
            Log.e(TAG, "Failed to JSONify AnsweredAssessment!");
            e.printStackTrace();
            return null;
        } catch (JSONException e) {
            Log.e(TAG, "Failed to put AnsweredAssessment to surveyResults!");
            e.printStackTrace();
            return null;
        } catch (UnsupportedEncodingException e) {
            Log.e(TAG, "Couldn't encode surveyResultsJSON!");
            e.printStackTrace();
            return null;
        } catch(Exception e) {
            Log.e(TAG,"Couldn't communicate with server while sending answers!" + e.getMessage());
            e.printStackTrace();
            return null;
        }

    }

    @Override
    protected void onPostExecute(String response) {

        if(this.myCallback == null) {
            Log.e(TAG, "Callback wasn't initialized first!");
            return;
        }

        if(response == null) {
            this.myCallback.onFailure(new Exception("Error occurred during transaction!"));
            return;
        }

        this.myCallback.onSuccess();

    }

}
