package uprrp.tania.activities;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import uprrp.tania.GlobalValues;
import uprrp.tania.R;
import uprrp.tania.networking.SendAccountRecovery;
import uprrp.tania.utils.URLEventListener;

public class AccountRecoveryActivity extends AppCompatActivity {

    private static final String TAG = "AccountRecoveryActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        // Start constructor
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_recovery);

        // Change all caps text to normal capitalization and add onClick listeners
        final Button recoverButton = findViewById(R.id.recoverButton);
        final Button forgotPasswordButton = findViewById(R.id.forgotPasswordButton);
        recoverButton.setTransformationMethod(null); // TODO: this is a workaround I found, any other acceptable solution is welcome
        forgotPasswordButton.setTransformationMethod(null); // TODO: this is a workaround I found, any other acceptable solution is welcome
        recoverButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendAccountRecoveryRequest();
            }
        });
        forgotPasswordButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AccountRecoveryActivity.this, ForgotPasswordActivity.class);
                startActivity(intent);
            }
        });

    }

    private void sendAccountRecoveryRequest() {

        final EditText emailText = findViewById(R.id.emailTextRecover);
        final EditText passwordText = findViewById(R.id.passwordTextRecover);

        // Email and password are needed (make sure user knows); else, proceed
        if(emailText.getText().toString().equals("") || passwordText.getText().toString().equals("")) {
            Toast.makeText(AccountRecoveryActivity.this, "All fields are needed!", Toast.LENGTH_LONG).show();
        } else {

            // Initiate progress dialog
            // TODO: find substitute for this deprecated dialog box
            final ProgressDialog progressDialog = ProgressDialog.show(AccountRecoveryActivity.this,
                    "Recovering Account",
                    "This shouldn't take long");

            // Send request to server
            SendAccountRecovery accountRecoveryTask = new SendAccountRecovery(new URLEventListener() {

                @Override
                public void onSuccess(String response) {

                    progressDialog.dismiss();
                    restoreConsentForm(response);

                    // Change user preferences to reflect login
                    Context context = AccountRecoveryActivity.this;
                    SharedPreferences prefs = context.getSharedPreferences("prefs", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = prefs.edit();
                    editor.putBoolean("needsToRegister", false);
                    editor.apply();

                    // Start MainActivity
                    Intent intent = new Intent(context, MainActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                    Toast.makeText(getApplicationContext(), "Login successful!", Toast.LENGTH_LONG).show();

                }

                @Override
                public void onFailure(Exception e) {
                    progressDialog.dismiss();
                    Toast.makeText(AccountRecoveryActivity.this, "Couldn't recover account!\nTry again later with the correct credentials...", Toast.LENGTH_LONG).show();
                    Log.e(TAG, "Error occurred while sending account recovery request to server...");
                    e.printStackTrace();
                }

            });

            // Start task
            String deviceToken = GlobalValues.getInstance().getDeviceToken();
            String email = emailText.getText().toString();
            String password = passwordText.getText().toString();
            accountRecoveryTask.execute(deviceToken, email, password);

        }

    }

    // TODO: IO should be moved to a background task
    private void restoreConsentForm(String response) {
        try {
            byte[] consentBytes = Base64.decode(response, Base64.NO_WRAP);
            FileOutputStream consentForm = new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + getString(R.string.consentFileName));
            consentForm.write(consentBytes);
            consentForm.close();
        } catch (FileNotFoundException e) {
            Log.e(TAG, "Couldn't find consent form (we were going to write to it)!");
            e.printStackTrace();
        } catch (IOException e) {
            Log.e(TAG, "Couldn't rewrite consent form!");
            e.printStackTrace();
        }
    }

}
