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.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import uprrp.tania.utils.URLEventListener;
import uprrp.tania.models.AssessmentModel;
import uprrp.tania.models.EmptyAssessmentModel;

public class FetchAssessment extends AsyncTask<String, Void, JSONObject> {

    private static final String TAG = "FetchAssessment";
    private static final String assessmentBaseURL = "https://tania.uprrp.edu/getSubQ2.php?tk=";
    private final URLEventListener myCallBack;

    public FetchAssessment(URLEventListener callback) {
        this.myCallBack = callback;
    }

    @Override
    protected JSONObject doInBackground(String... deviceTokenArray) {
        String deviceToken = deviceTokenArray[0]; // array will only ever contain a single element

        try {

            URL url = new URL(assessmentBaseURL + deviceToken);
            Log.d(TAG, "token:" + deviceToken); // log
            Log.d(TAG, "url:" + url.toString()); // log
            HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
            InputStream inputStream = httpsURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder serverResponse =  new StringBuilder();

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

            String response = serverResponse.toString();
            Log.d(TAG, response.substring(0, 10)); // log
            if(response.startsWith("Error:NoHa")) {
                return new JSONObject("{}");
            } else {
                return new JSONObject(response);
            }

        } catch (MalformedURLException e) {
            Log.e(TAG, "Wrong URL used!");
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            Log.e(TAG, "IOStream error occurred!");
            e.printStackTrace();
            return null;
        } catch (JSONException e) {
            Log.e(TAG, "Couldn't construct return JSON!");
            e.printStackTrace();
            return null;
        }

    }

    @Override
    protected void onPostExecute(JSONObject obj) {

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

        if(obj == null) {
            this.myCallBack.onFailure(new Exception("An error occurred during FetchAssessment!"));
            return;
        }

        // If there's no survey available, return empty AssessmentModel
        if(obj.length() == 0) {
            Log.d(TAG, "SENT EMPTY ASSESSMENT MODEL");
            AssessmentModel assessment = new EmptyAssessmentModel();
            this.myCallBack.onSuccess(assessment);
            return;
        }

        // Decode into AssessmentModel and send
        try {
            Log.d(TAG, "rawString:" + obj.toString());
            GsonBuilder builder = new GsonBuilder();
            builder.setPrettyPrinting();
            AssessmentModel assessment = builder.create().fromJson(obj.toString(), AssessmentModel.class);
            Log.d(TAG,"reconstructedJSON:\n" + builder.create().toJson(assessment));
            this.myCallBack.onSuccess(assessment);
        } catch (JsonSyntaxException e) {
            this.myCallBack.onFailure(new Exception("Something went wrong during data preparation step in FetchAssessment.onPostExecute()!"));
        }

    }

}


