package com.dowerx.quack.service;

import android.Manifest;
import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Build;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;

import com.dowerx.quack.R;
import com.dowerx.quack.activity.MainActivity;
import com.dowerx.quack.activity.SwitcherActivity;
import com.google.android.gms.tasks.Tasks;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.FirebaseFirestore;

import java.util.HashMap;
import java.util.concurrent.ExecutionException;

public class AuthService {
    public static String getId() {
        return id;
    }

    private static String id;

    // email, password
    public static class Login extends AsyncTask<String, Void, Boolean> {
        Activity activity;

        public Login(Activity activity) {
            this.activity = activity;
        }

        @Override
        protected Boolean doInBackground(String... loginDetails) {
            FirebaseAuth fba = FirebaseAuth.getInstance();
            try {
                AuthResult result = Tasks.await(fba.signInWithEmailAndPassword(loginDetails[0], loginDetails[1]));
                id = result.getUser().getUid();
                return true;
            } catch (ExecutionException | InterruptedException e) {
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean result) {

            if (result) {
                activity.startActivity(new Intent(activity, SwitcherActivity.class));
            } else {
                Toast toast = new Toast(activity.getBaseContext());
                toast.setText("login failed");
                toast.setDuration(Toast.LENGTH_LONG);
                toast.show();
            }
        }
    }

    // email, password, username
    public static class Register extends AsyncTask<String, Void, Boolean> {
        Activity activity;

        public Register(Activity activity) {
            this.activity = activity;
        }

        @Override
        protected Boolean doInBackground(String... loginDetails) {
            FirebaseAuth fba = FirebaseAuth.getInstance();
            try {
                AuthResult result = Tasks.await(fba.createUserWithEmailAndPassword(loginDetails[0], loginDetails[1]));

                FirebaseFirestore ffs = FirebaseFirestore.getInstance();
                HashMap<String, String> data = new HashMap<>();
                data.put("email", loginDetails[0]);
                data.put("username", loginDetails[2]);
                data.put("picture", "/assets/placeholder-profile-picture.png");
                data.put("id", result.getUser().getUid());

                ffs.collection("user").document(loginDetails[2]).set(data);

                return true;
            } catch (ExecutionException | InterruptedException e) {
                return false;
            }
        }

        @RequiresApi(api = Build.VERSION_CODES.TIRAMISU)
        @Override
        protected void onPostExecute(Boolean result) {
            if (result) {
                Toast toast = new Toast(activity.getBaseContext());
                toast.setText("succesful register");
                toast.setDuration(Toast.LENGTH_LONG);
                toast.show();

                NotificationCompat.Builder builder = new NotificationCompat.Builder(activity.getApplicationContext(), "register")
                    .setSmallIcon(R.mipmap.ic_launcher_round)
                    .setContentTitle("Welcome to Quack!")
                    .setContentText("Thank you for registering!")
                    .setPriority(NotificationCompat.PRIORITY_LOW);

                if (ActivityCompat.checkSelfPermission(activity.getApplicationContext(), Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                    String[] permissions = new String[1];
                    permissions[0] = Manifest.permission.POST_NOTIFICATIONS;
                    ActivityCompat.requestPermissions(activity, permissions, 0);
                }

                NotificationManager manager = (NotificationManager) activity.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
                manager.notify(0, builder.build());

                activity.startActivity(new Intent(activity, MainActivity.class));
            } else {
                Toast toast = new Toast(activity.getBaseContext());
                toast.setText("register failed");
                toast.setDuration(Toast.LENGTH_LONG);
                toast.show();
            }
        }
    }
}
