package org.keyscience.app;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

import org.keyscience.BackgroundTask.UpdateProfileTask;
import org.keyscience.Gravatar.MD5Util;
import org.keyscience.R;
import org.keyscience.SingletonPattern.User;
import org.keyscience.picasso.CircleTransform;

import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;


public class ProfileUpdateActivity extends AppCompatActivity {

    private EditText user_name;
    private EditText user_bio;

    private String enteredPassword = "";

    private Button submitButton;
    private Button imageButton;

    private ImageView imageView;
    private UpdateProfileTask task;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.profile_update_layout);

        user_name = findViewById(R.id.name);
        user_bio = findViewById(R.id.bio);

        imageButton = findViewById(R.id.image_button);
        submitButton = findViewById(R.id.profile_submit);

        imageView = findViewById(R.id.profile_image);

        user_name.setText(User.getInstance().getName());
        user_bio.setText(User.getInstance().getBio());

        imageSelect();
        updateProfileImage();
        profileSetup();
    }

    public void imageSelect() {
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Link out to https://en.gravatar.com/connect/
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://en.gravatar.com/connect/"));
                startActivity(browserIntent);
            }
        });
    }

    public void profileSetup() {
        submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(ProfileUpdateActivity.this);
                builder.setTitle("Please enter your Password: ");

                // Set up the input
                final EditText input = new EditText(ProfileUpdateActivity.this);

                // Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
                input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                builder.setView(input);

                // Set up the buttons
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        enteredPassword = input.getText().toString();
                        updateProfileDetails();
                    }
                });
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

                builder.show();
            }
        });
    }

    private void updateProfileDetails() {

        Toast.makeText(ProfileUpdateActivity.this, "Updating..", Toast.LENGTH_SHORT).show();

        String user_password = enteredPassword;
        String user_email = User.getInstance().getEmail();

        task = new UpdateProfileTask(user_name.getText().toString(),
                user_bio.getText().toString(), this);
        task.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, user_email, user_password);

    }

    @Override
    protected void onPause() {
        if (task != null) {
            task.cancel(true);
            try {
                //Waits if necessary to complete
                task.get();
            } catch (ExecutionException e) {
                //  ignore
            } catch (InterruptedException e) {
                //  ignore
            } catch (CancellationException e) {
                //  ignore
            }
            task = null;
        }
        super.onPause();
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();

        updateProfileImage();
    }

    private void updateProfileImage() {

        String userEmail = User.getInstance().getEmail();
        String hash = MD5Util.md5Hex(userEmail);
        String gravatarUrl = "http://www.gravatar.com/avatar/" + hash + "?s=204&d=404";

        Picasso.get()
                .load(gravatarUrl)
                .transform(new CircleTransform())
                .placeholder(R.mipmap.ic_launcher_round)
                .resize(200, 200)
                .centerInside()
                .noFade()
                .into(imageView);
    }

}
