package uprrp.tania.networking;

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

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

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.models.UserModel;
import uprrp.tania.utils.URLEventListener;

public class SendUserRegistration extends AsyncTask <UserModel, Void, String> {

    private static final String TAG = "SendUserRegistration";
    private static final String sendUserRegistrationURL = "https://tania.uprrp.edu/registrationAnd.php";
    private final URLEventListener myCallback;

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

    private boolean validInputs(UserModel... users) {

        if(users.length != 1) {
            Log.e(TAG, "Invalid array length!");
            return false;
        }

        for(int i = 0; i < users.length; i++) {
            if(users[i] == null) {
                Log.e(TAG, "Encountered null parameter on index " + i);
                return false;
            }
        }

        return true;

    }

    // 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:
        {
            "email": String,
            "birthDate": String,
            "password": String,
            "gender": String,
            "hasJob": String,
            "token": String
        }
    */
    @Override
    protected String doInBackground(UserModel... users) {

        // Validation
        if(!validInputs(users)) {
            Log.e(TAG, "Invalid inputs given!");
            return null;
        }

        // Extract variables
        UserModel user = users[0];

        try {

            // Serialize user
            GsonBuilder builder = new GsonBuilder();
//            builder.setPrettyPrinting(); // the server doesn't like pretty printing...
            String serializedUser = builder.create().toJson(user);
            Log.d(TAG,"RegistrationJSON is \n" + serializedUser);

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

            // Send POST data request
            URL url = new URL(sendUserRegistrationURL);
            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();
//            String response = "lkajhkljsdhlakjsdhaf";
            Log.d(TAG, "The server's response is: " + response);
            if(response.contains("Success")) {
                return response;
            } else {
                return null;
            }

        } catch (JsonSyntaxException e) {
            Log.e(TAG, "Failed to JSONify User!");
            e.printStackTrace();
            return null;
        } catch (UnsupportedEncodingException e) {
            Log.e(TAG, "Couldn't encode registrationJSON!");
            e.printStackTrace();
            return null;
        } catch(Exception e) {
            Log.e(TAG,"Couldn't communicate with server while sending user registration!" + 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();

    }

}
