package uprrp.tania.activities;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.util.Observable;
import java.util.Observer;

import uprrp.tania.GlobalValues;
import uprrp.tania.R;
import uprrp.tania.URLEventListener;
import uprrp.tania.networking.SendExperienceRegistration;

public class ExperienceRegistrationActivity  extends AppCompatActivity implements Observer {

    private static final String TAG = "ExperienceRegistrationActivity";
    private String EXPERIENCE_ID;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

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

        // Fetch experience ID from URL (only if we launched this Activity from Browser)
        Intent intent = getIntent();
        if(Intent.ACTION_VIEW.equals(intent.getAction())) {
            Uri uri = intent.getData();
            assert uri != null; // TODO: figure out if this causes crashes...
            EXPERIENCE_ID = uri.getQueryParameter("id");
            Log.wtf("EXPERIENCE ID", EXPERIENCE_ID);
        }

        // Listen for device token changes
        this.startObservingGlobals();

        // Disable interaction initially while token is being fetched
        if(GlobalValues.getInstance().getDeviceToken() == null) {
            Log.wtf("EXPERIENCE ID", "DISABLING");
            disableInteractionTemporarily();
        } else {
            enableInteraction();
        }

        // Change all caps text to normal capitalization and add onClick listener
        final Button experienceRegistrationButton = findViewById(R.id.buttonEnterExperience);
        experienceRegistrationButton.setTransformationMethod(null); // TODO: this is a workaround I found, any other acceptable solution is welcome
        experienceRegistrationButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendRegistrationRequest();
            }
        });

    }

    // TAKEN FROM https://stackoverflow.com/questions/21886768/is-there-any-method-i-can-listen-for-changes-to-global-variable-to-trigger-an-ev
    private void startObservingGlobals() {
        GlobalValues.getInstance().addObserver(this);
    }

    // TAKEN FROM https://stackoverflow.com/questions/21886768/is-there-any-method-i-can-listen-for-changes-to-global-variable-to-trigger-an-ev
    @Override
    public void update(Observable observable, Object o) {
        if(observable instanceof GlobalValues) {
            if(o instanceof GlobalValues.ValueKey) {
                if(((GlobalValues.ValueKey) o).getKey() == GlobalValues.ValueName.DEVICE_TOKEN) {
                    if(GlobalValues.getInstance().getDeviceToken() == null) {
                        disableInteraction();
                    } else {
                        enableInteraction();
                    }
                }
            }
        }
    }

    private void enableInteraction() {
        final Button experienceRegistrationButton = findViewById(R.id.buttonEnterExperience);
        final TextView experienceRegistrationTextView = findViewById(R.id.experienceRegistrationText);

        experienceRegistrationButton.setEnabled(true);
        experienceRegistrationTextView.setText(R.string.experienceRegistrationDescriptionText);
    }

    private void disableInteraction() {
        final Button experienceRegistrationButton = findViewById(R.id.buttonEnterExperience);
        final TextView experienceRegistrationTextView = findViewById(R.id.experienceRegistrationText);

        experienceRegistrationButton.setEnabled(false);
        experienceRegistrationTextView.setText(R.string.tokenErrorText);
    }

    private void disableInteractionTemporarily() {
        final Button experienceRegistrationButton = findViewById(R.id.buttonEnterExperience);
        final TextView experienceRegistrationTextView = findViewById(R.id.experienceRegistrationText);

        experienceRegistrationButton.setEnabled(false);
        experienceRegistrationTextView.setText(R.string.loadingText);
    }

    private void sendRegistrationRequest() {

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

        // Send registration request to server
        SendExperienceRegistration experienceRegistrationTask = new SendExperienceRegistration(new URLEventListener() {
            @Override
            public void onSuccess() {
                progressDialog.dismiss();
                Context context = ExperienceRegistrationActivity.this;
                Intent intent = new Intent(context, MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
                Toast.makeText(getApplicationContext(), "You have been registered!", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFailure(Exception e) {
                progressDialog.dismiss();
                Toast.makeText(ExperienceRegistrationActivity.this, "Oops! Something went wrong...\nPlease try again", Toast.LENGTH_LONG).show();
                Log.e(TAG, "Error occurred while sending registration request to server...");
                e.printStackTrace();
            }
        });

        experienceRegistrationTask.execute(GlobalValues.getInstance().getDeviceToken(), this.EXPERIENCE_ID);

        // UNCOMMENT THIS FOR TESTING (REMEMBER TO COMMENT .execute() LINE)
        /*
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            public void run() {
                progressDialog.dismiss();
                if(false) { // Imitate success
                    Context context = ExperienceRegistrationActivity.this;
                    Intent intent = new Intent(context, MainActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                    Toast.makeText(getApplicationContext(), "You have been registered!", Toast.LENGTH_LONG).show();
                } else { // Imitate failure
                    Toast.makeText(ExperienceRegistrationActivity.this, "Oops! Something went wrong...", Toast.LENGTH_LONG).show();
                }
            }
        }, 5000);
        */
        // UNCOMMENT THIS FOR TESTING (REMEMBER TO COMMENT .execute() LINE)

    }

}
