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.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

import uprrp.tania.utils.URLEventListener;

public class SendResetPassword extends AsyncTask <String, Void, String> {

    private static final String TAG = "SendResetPassword";
    private static final String resetPasswordBaseURL = "https://tania.uprrp.edu/resetPassword.php";
    private final URLEventListener myCallback;

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

    private boolean validInputs(String... strings) {

        if(strings.length != 3) {
            Log.e(TAG, "Invalid string array length!");
            return false;
        }

        for(int i = 0; i < strings.length; i++) {
            if(strings[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:
        {
            "forgotPasswordKey": String,
            "password": String,
            "token": String,
        }
    */
    @Override
    protected String doInBackground(String... strings) {

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

        // Extract variables
        String deviceToken = strings[0];
        String newPassword = strings[1];
        String forgotPasswordKey = strings[2];

        try {

            // Create JSON
            JSONObject resetPasswordJSON = new JSONObject();
            resetPasswordJSON.put("token", deviceToken);
            resetPasswordJSON.put("password", newPassword);
            resetPasswordJSON.put("forgotPasswordKey", forgotPasswordKey);
            Log.d(TAG, "resetPasswordJSON is " + resetPasswordJSON.toString());

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

            // Send POST data request
            URL url = new URL(resetPasswordBaseURL);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            Writer writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8));
            writer.write(encodedRequestBody);
            writer.close();

            // 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.contains("Success")) {
                return response;
            } else {
                return null;
            }

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

    }
}
