package com.example.epl498_labs.ui.location;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;

import com.example.epl498_labs.R;
import com.example.epl498_labs.databinding.FragmentLocationBinding;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;

public class LocationFragment extends Fragment {

    private FragmentLocationBinding binding;
    private FusedLocationProviderClient fusedLocationClient;

    // Use ActivityResultLauncher to request permission
    private ActivityResultLauncher<String> requestPermissionLauncher =
            registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
                if (isGranted) {
                    // Permission is granted. Get the location.
                    getLastLocation();
                } else {
                    // Permission denied. Handle this situation.
                    binding.textviewLongitude.setText(R.string.location_not_granted);
                    binding.textviewLatitude.setText("");
                }
            });

    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(requireActivity());

        binding = FragmentLocationBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        binding.buttonUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Firstly, check that we have permission to get the location
                if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_FINE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED) {
                    // Permission is not granted. Request it using ActivityResultLauncher.
                    requestPermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION);
                } else {
                    // Permission is granted. Get the location.
                    getLastLocation();
                }
            }
        });

        // setting on click listener to navigate to second fragment
        binding.buttonGeofence.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NavHostFragment.findNavController(LocationFragment.this)
                        .navigate(R.id.action_LocationFragment_to_GeofenceFragment);
            }
        });
    }

    private void getLastLocation() {
        // If we have the permission to get the location
        if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            fusedLocationClient.getLastLocation()
                    .addOnSuccessListener(requireActivity(), new OnSuccessListener<Location>() {
                        @Override
                        public void onSuccess(Location location) {
                            if (location != null) {
                                // Update the TextViews with latitude and longitude
                                binding.textviewLongitude.setText("Longitude: " + location.getLongitude());
                                binding.textviewLatitude.setText("Latitude: " + location.getLatitude());
                            }
                        }
                    });
        } else {
            binding.textviewLongitude.setText(R.string.location_not_granted);
            binding.textviewLatitude.setText("");
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}
