package com.androiddev.project.ili.wishurgift.activities;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.Response;
import com.androiddev.project.ili.wishurgift.R;
import com.androiddev.project.ili.wishurgift.api.UserApi;
import com.google.android.material.snackbar.Snackbar;
import com.mobsandgeeks.saripaar.ValidationError;
import com.mobsandgeeks.saripaar.Validator;
import com.mobsandgeeks.saripaar.annotation.Email;
import com.mobsandgeeks.saripaar.annotation.NotEmpty;
import com.mobsandgeeks.saripaar.annotation.Password;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;


public class RegisterActivity extends AppCompatActivity implements Validator.ValidationListener {

    @NotEmpty(trim = true)
    EditText editTextUsername;

    @NotEmpty(trim = true)
    @Email
    EditText  editTextEmail;

    private ProgressDialog pg;



    @Password(min = 8 , scheme = Password.Scheme.ALPHA_NUMERIC_MIXED_CASE_SYMBOLS, message = "Passwords must be at least 8 characters long, have an upper-case letter, a lower-case letter, a number and a \"special character\". ")
    EditText editTextPassword;

    private Button mEmailRegisterButton;

    private Validator validator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        mEmailRegisterButton = findViewById(R.id.cirRegisterButton);
        editTextUsername = findViewById(R.id.editTextName);
        editTextEmail = findViewById(R.id.email_signin);
        editTextPassword = findViewById(R.id.password_signup);

        validator = new Validator(this);
        validator.setValidationListener(this);

        mEmailRegisterButton.setOnClickListener(v -> validator.validate(true));

    }

    public void onLoginClick(View view) {
        startActivity(new Intent(this, LoginActivity.class));
        overridePendingTransition(R.anim.slide_in_left, android.R.anim.slide_out_right);

    }

    /**
     * Inscrit l'utilisateur, en cas d'erreur affiche un message à l'utilisateur
     */
    private void attemptRegister() {
        //showProgress(true);
        onPreExecute();
        UserApi.signIn(editTextUsername.getText().toString(), editTextEmail.getText().toString(), editTextPassword.getText().toString(), (Response.Listener<JSONObject>) response -> {

            try {
                if (response.getBoolean("success")) {
                    onLoginClick(null);
                    pg.dismiss();
                }
            } catch (JSONException e) {
                Log.d("error", e.getMessage());
            }
        }, error -> {
            pg.hide();
            Log.d("error", error.toString());
            AlertDialog.Builder alertDialogBuilder=new AlertDialog.Builder(this);
            alertDialogBuilder.setTitle("Unable to register");
            alertDialogBuilder.setMessage("You are not connected to the Internet or your email may be already used.\nIf the problem persist, contact the administrator").setCancelable(false).setNeutralButton("Ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            AlertDialog alertDialog =alertDialogBuilder.create();
            alertDialog.show();
        });
    }

    @Override
    public void onValidationSucceeded() {
        attemptRegister();
    }

    @Override
    public void onValidationFailed(List<ValidationError> errors) {
        for (ValidationError error : errors) {
            View view = error.getView();
            String message = error.getCollatedErrorMessage(this);

            if (view instanceof EditText) {
                ((EditText) view).setError(message);
            } else {
                Snackbar.make(view, message, Snackbar.LENGTH_LONG).setAction(message, null).show();
            }
        }
    }

    private void onPreExecute() {
        if(pg==null){
            pg = new ProgressDialog(this, R.style.AppTheme_Dark_Dialog);
        }
        pg.setTitle("account creation in progress...");
        pg.setMessage("Please wait.");
        pg.setCancelable(false);
        pg.setIndeterminate(true);
        pg.show();

    }
}
