package virgo.findyourfate.com;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicReference;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;

import android.os.Handler;
import android.os.Looper;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Button;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.messaging.FirebaseMessaging;



public class RegisterActivity extends Activity {

    Button btnGCMRegister;
    Button btnAppShare;

    Context context;
    String regId;

    public static final String PROPERTY_REG_ID  = "regId";
    private static final String APP_VERSION = "appVersion";

    static final String TAG = "Register Activity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            // Enable the home button and set display options
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_SHOW_CUSTOM);

            // Set the title of the ActionBar
            actionBar.setTitle(Html.fromHtml("<font color=\"#ffffff\" size=\"21px\"><b>Virgo</b></font>"));

            // Enable the home button for backward compatibility
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                actionBar.setHomeButtonEnabled(true);
            }

            // Show the ActionBar
            actionBar.show();
        }
        context = getApplicationContext();
        regId = registerGCM();

    }

    private ActionBar getSupportActionBar() {
        return null;
    }

    public String registerGCM() {

        FirebaseMessaging.getInstance().getToken()
                .addOnCompleteListener(task -> {
                    if (!task.isSuccessful()) {
                        Log.w("RegisterActivity", "Fetching FCM registration token failed", task.getException());
                        return;
                    }

                    // Get the FCM token
                    String token = task.getResult();
                    Log.d("RegisterActivity", "FCM Token: " + token);

                    // Store or send the token to your server
                    storeRegistrationId(context, token);
                });

        if (TextUtils.isEmpty(regId)) {

            registerInBackground();

        } else {
        }

        return regId;
    }

    private String getRegistrationId(Context context) {
        final SharedPreferences prefs = getGCMPreferences(context);

        String registrationId = prefs.getString(PROPERTY_REG_ID , "");
        if (registrationId.isEmpty()) {
            Log.i(TAG, "Registration not found.");
            return "";
        }
        int registeredVersion = prefs.getInt(APP_VERSION, Integer.MIN_VALUE);
        int currentVersion = getAppVersion(context);
        if (registeredVersion != currentVersion) {
            // Log.i(TAG, "App version changed.");
            return "";
        }
        return registrationId;
    }
    private SharedPreferences getGCMPreferences(Context context) {
        // This sample app persists the registration ID in shared preferences, but
        // how you store the regID in your app is up to you.
        return getSharedPreferences(RegisterActivity.class.getSimpleName(),
                Context.MODE_PRIVATE);
    }
    private static int getAppVersion(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (NameNotFoundException e) {
            Log.d("RegisterActivity",
                    "I never expected this! Going down, going down!" + e);
            throw new RuntimeException(e);
        }
    }

    @SuppressLint("StaticFieldLeak")
    private void registerInBackground() {
        new AsyncTask<Void, Void, String>() {

            @Override
            protected String doInBackground(Void... params) {
                AtomicReference<String> msg = new AtomicReference<>("");
                try {
                    FirebaseMessaging.getInstance().getToken()
                            .addOnCompleteListener(task -> {
                                if (!task.isSuccessful()) {
                                    Log.w("RegisterActivity", "Fetching FCM registration token failed", task.getException());
                                    return;
                                }

                                // Get the FCM token
                                regId = task.getResult();
                                Log.d("RegisterActivity", "registerInBackground - regId: " + regId);
                                msg.set("Device registered, registration ID=" + regId);

                                // Store the token for future use
                                storeRegistrationId(context, regId);

                                // Start the next activity on the main thread
                                new Handler(Looper.getMainLooper()).post(() -> {
                                    Intent i = new Intent(context, MainActivityfirst.class);
                                    i.putExtra("regId", regId);
                                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // Add flag if context is not an Activity
                                    context.startActivity(i);
                                });
                            });
                } catch (Exception ex) {
                    msg.set("Error: " + ex.getMessage());
                    Log.d("RegisterActivity", "Error: " + msg);

                    // Handle error case on the main thread
                    new Handler(Looper.getMainLooper()).post(() -> {
                        Intent i = new Intent(context, MainActivityfirst.class);
                        i.putExtra("regId", regId);
                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(i);
                    });
                }
                Log.d("RegisterActivity", "AsyncTask completed: " + msg);
                return msg.get();
            }

            @Override
            protected void onPostExecute(String msg) {
                // Toast.makeText(getApplicationContext(),  "Registered with GCM Server." + msg, Toast.LENGTH_LONG).show();
            }
        }.execute(null, null, null);
    }

    private void storeRegistrationId(Context context, String regId) {
        final SharedPreferences prefs = getSharedPreferences(
                MainActivityfirst.class.getSimpleName(), Context.MODE_PRIVATE);
        int appVersion = getAppVersion(context);
        Log.i(TAG, "Saving regId on app version " + appVersion);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(PROPERTY_REG_ID , regId);
        editor.putInt(APP_VERSION, appVersion);
        editor.commit();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Exit!");
        builder.setMessage("Are you sure you want to exit from Virgo app?")
                .setCancelable(false)
                .setIcon(R.drawable.alert)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.addCategory(Intent.CATEGORY_HOME);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }
}