package uprrp.tania.networking;

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

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;

public class SendExperienceRegistration extends AsyncTask<String, String, String> {

    private static final String TAG = "SendActivateExperience";
    private static final String activateExperienceURL = "https://tania.uprrp.edu/inscripcionExperiencia.php";
    private final URLEventListener myCallback;

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

    // TODO: instead of making a normal POST request with
    //  the body data=<JSON>, we should just send the JSON itself
    //  This is adding unnecessary layers of complexity when decoding AND encoding
    /*
        JSON format:
        {
            "token": String,
            "id_experiencia": String
        }
    */
    @Override
    protected String doInBackground(String... strings) {

        String deviceToken = strings[0];
        String experienceID = strings[1];

        if(experienceID == null) {
            Log.e(TAG, "Encountered null experience ID!");
            return null;
        } else if (deviceToken == null) {
            Log.e(TAG, "Encountered null device token!");
            return null;
        }

        try {

            // Create JSON
            JSONObject experienceRegistrationJSON = new JSONObject();
            experienceRegistrationJSON.put("token", deviceToken);
            experienceRegistrationJSON.put("id_experiencia", experienceID);
            Log.d(TAG, "Prepared JSON: " + experienceRegistrationJSON.toString());

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

            // Send POST data request
            URL url = new URL(activateExperienceURL);
            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();
            }

            // TODO: restrict double registration (maybe in backend?)
            String response = serverResponse.toString();
            Log.d(TAG, "The server's response is: " + response);
            if(response.startsWith("Success")) {
                return response;
            } else {
                return null;
            }

        } catch (JSONException e) {
            Log.e(TAG, "Couldn't prepare experienceRegistrationJSON!");
            e.printStackTrace();
            return null;
        } catch (UnsupportedEncodingException e) {
            Log.e(TAG, "Couldn't encode experienceRegistrationJSON!");
            e.printStackTrace();
            return null;
        } catch(Exception e) {
            Log.e(TAG, "Couldn't communicate with server while activating experience!");
            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();

    }

}
