/*************************************************************
 * By: Coralys Cubero Rivera
 * Date: 2019
 *************************************************************/

package uprrp.tania;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;

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

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

    private Context context;

    public SendLoginToServer(Context context){
        this.context = context.getApplicationContext();
    }

    @Override
    protected String doInBackground(String... strings) {

        String json  = null;
        try {
            json = URLEncoder.encode("data", "UTF-8") + "=" + URLEncoder.encode(strings[0], "UTF-8");
            Log.d("RECOVER ACCOUNT", json);
        } catch (UnsupportedEncodingException e) {
            Log.e("RECOVER ACCOUNT ERROR", e.getMessage());
        }

        String text = "";
        BufferedReader reader = null;

        // Send data
        try
        {
            // Defined URL  where to send data
            URL url = new URL("https://tania.uprrp.edu7/recoverAccount.php");

            // Send POST data request
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            assert json != null;
            wr.write(json);
            wr.flush();

            // Get the server response
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;

            // Read Server Response
            while((line = reader.readLine()) != null)
            {
                // Append server response in string
                sb.append(line).append("\n");
            }

            text = sb.toString();
        }
        catch(Exception ex) {
            Log.e("RECOVER ACCOUNT ERROR", ex.getMessage());
        }
        finally
        {
            try
            {
                assert reader != null;
                reader.close();
            }
            catch(Exception ex) {
                Log.e("RECOVER ACCOUNT ERROR", ex.getMessage());
            }
        }

        return text;

    }

    @Override
    protected void onPostExecute(String s) {
        Log.d("RECOVER ACCOUNT RESPOND", "The server's response is: " + s);

        String se = s.substring(0, 5);
        if (!se.equals("Error")) {

            try {

                FileOutputStream consentForm = new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/consent-tania-app.pdf");

                byte[] consentBytes = Base64.decode(s, Base64.NO_WRAP);
                consentForm.write(consentBytes);
                consentForm.close();

                SharedPreferences prefs = context.getSharedPreferences("prefs", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();
                editor.putBoolean("needsToRegister", false);
                editor.apply();

                Intent intent = new Intent(context, MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);

            } catch (IOException e) {
                Log.e("RECOVER CONSENT LOGIN", "File not found!");
            }
        }

        else
            {
                Toast.makeText(context, "Can't recover account! Try again later. ", Toast.LENGTH_LONG).show();
            }
        }



}
