package com.app.simplitend.patient_dashboard;

import static com.app.simplitend.patientgeofencing.GeoFenceHelper.GEOFENCE_TAG;

import android.Manifest;
import android.app.role.RoleManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.telecom.TelecomManager;
import android.util.Log;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import com.app.simplitend.R;
import com.app.simplitend.apputils.AppUtil;
import com.app.simplitend.apputils.PatientDataCache;
import com.app.simplitend.caregiverdashboard.mvvm.CgHomeContracts;
import com.app.simplitend.caregiverdashboard.mvvm.models.GeoFenceDetails;
import com.app.simplitend.chats.SocketHelper;

public class DashBoardActivity extends AppCompatActivity implements CgHomeContracts.GetGeoFenceCallback {

    protected PatientMainViewModel viewModel;

    protected ActivityResultLauncher<String> finePermissionLauncher;
    protected ActivityResultLauncher<String> backgroundPermissionLauncher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dash_board_cp);

        viewModel = new ViewModelProvider(this).get(PatientMainViewModel.class);

        finePermissionLauncher = registerForActivityResult(new ActivityResultContracts.RequestPermission(),
                isGranted -> {
                    if (isGranted) {
                        // fine location permission is granted
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                            if (checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) != PackageManager.PERMISSION_GRANTED){
                                AppUtil.showSOSDecision(this,
                                        "To enable caregivers to receive notifications even when the app is closed, go to the settings menu and select allow all the time",
                                        "Settings", "No thanks", view -> {
                                            // Settings click
                                            backgroundPermissionLauncher.launch(Manifest.permission.ACCESS_BACKGROUND_LOCATION);
                                        }, view -> {
                                            // No thanks click
                                            Toast.makeText(this, "Geofencing is off.", Toast.LENGTH_SHORT).show();
                                        });
                            }else{
                                setGeofenceAndLocationUpdates();
                            }
                        } else {
                            setGeofenceAndLocationUpdates();
                        }

                        // getting location updates
                        viewModel.addLocationUpdates(this);
                    } else {
                        // permission denied
                        AppUtil.showAlert(this,
                                "We understand your privacy",
                                "To connect you with your guardian allow SimpliTend to access your location",
                                "Allow",
                                ((dialogInterface, i) -> {
                                    finePermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION);
                                }), null, null);
                    }
                });

        backgroundPermissionLauncher = registerForActivityResult(new ActivityResultContracts.RequestPermission(),
                isGranted -> {
                    if (isGranted) {
                        setGeofenceAndLocationUpdates();
                    }
                });

        registerForActivityResult(new ActivityResultContracts.RequestPermission(),
                result -> {

                    // reigstering geofencing
                    // thus, asking for permission
                    finePermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION);

                    if (result) {
                        // permission granted
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                            RoleManager roleManager = getSystemService(RoleManager.class);
                            Intent i = roleManager.createRequestRoleIntent(RoleManager.ROLE_CALL_SCREENING);
                            startActivityForResult(i, 1214, null);
                        } else {
                            Intent intent = new Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER);
                            intent.putExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME, getPackageName());
                            startActivity(intent);
                        }
                    }
                }).launch(Manifest.permission.READ_CONTACTS);
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        final Configuration configuration = new Configuration(newBase.getResources().getConfiguration());
        configuration.fontScale = Math.min(configuration.fontScale, 1.1f);
        applyOverrideConfiguration(configuration);
        super.attachBaseContext(newBase);
    }

    private void setGeofenceAndLocationUpdates() {
        // retrieving geofence
        viewModel.getGeoFenceDetails(AppUtil.getPatientUid(this) + "",
                "", "Bearer " + AppUtil.getPatientToken(this),
                this);
    }

    public void validateAndAddGeofence(GeoFenceDetails geoFenceDetails) {
        if (geoFenceDetails.radius != null && geoFenceDetails.type != null) {
            PatientDataCache.getPatientData(this, (patientData -> {
                if (patientData != null) {
                    if (AppUtil.shouldAddPatientGeofence(this,
                            geoFenceDetails.radius, geoFenceDetails.type, patientData)) {
                        // should add a geofence
                        viewModel.setGeofence(this, geoFenceDetails, patientData);
                    } else {
                        Log.d(GEOFENCE_TAG, "onGeofenceDetailsFetched: should not add patient geofence because GEOFENCE DETAILS: " + geoFenceDetails + " PATIENT DETAILS: " + patientData);
                    }
                }
            }), false);
        }

    }

    @Override
    public void onGeofenceDetailsFetched(@NonNull GeoFenceDetails geoFenceDetails) {
        validateAndAddGeofence(geoFenceDetails);
    }
    @Override
    public void onGeofenceDetailsFetchFailed(Throwable throwable, String message) {
        Log.d(GEOFENCE_TAG, "onGeofenceDetailsFetchFailed: " + message);

    }
}