package com.ads.cal.calculator.utils;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;

import androidx.core.app.ActivityCompat;

import com.ads.cal.calculator.MyApplication;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class LocationMgr {


    private LocationManager locationManager;
    private List<LocationListener> locationListeners; // 存储监听器列表
    private final LocationCallback locationCallback;
    private boolean isRequestingLocation;
    private final Handler handler = new Handler(Looper.getMainLooper());

    public LocationMgr(LocationCallback callback) {
        this.locationCallback = callback;
        locationListeners = new ArrayList<>(); // 初始化监听器列表
    }

    public void startLocation() {
        if (ActivityCompat.checkSelfPermission(MyApplication.getApplication(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(MyApplication.getApplication(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // 如果没有定位权限，请求权限
            // 此处可以添加代码来请求权限
            return;
        }
        FireBaseAnalyticsUtils.init().send(EventIdUtils.COMPASS_LOCATION_START);
        locationManager = (LocationManager) MyApplication.getApplication().getSystemService(Context.LOCATION_SERVICE);
        List<String> list = locationManager.getProviders(true);

        if (list == null || list.isEmpty()) {
            // 没有可用的定位提供程序
            FireBaseAnalyticsUtils.init().send(EventIdUtils.COMPASS_LOCATION_ENABLE);
            return;
        }

        isRequestingLocation = true;

        // 停止之前的监听器
        stopPreviousLocationUpdates();

        for (int i = 0; i < list.size(); i++) {
            Location location = locationManager.getLastKnownLocation(list.get(i));
            if (location != null) {
                updateLocation(location);
                break;
            }
            LocationListener locationListener = getLocationListener();
            locationListeners.add(locationListener); // 将监听器添加到列表
            locationManager.requestSingleUpdate(list.get(i), locationListener, null);
        }

        // 使用Handler来延迟停止定位请求
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                stopLocationUpdates();
            }
        }, 12000); // 12秒
    }

    private void stopPreviousLocationUpdates() {
        if (!locationListeners.isEmpty()) {
            for (LocationListener listener : locationListeners) {
                locationManager.removeUpdates(listener); // 停止每个监听器
            }
            locationListeners.clear(); // 清空监听器列表
        }
    }

    public void stopLocationUpdates() {
        if (isRequestingLocation) {
            stopPreviousLocationUpdates(); // 停止之前的监听器
            isRequestingLocation = false;
        }
    }

    private LocationListener getLocationListener() {
        return new LocationListener() {
            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }

            @Override
            public void onProviderEnabled(String provider) {
            }

            @Override
            public void onProviderDisabled(String provider) {
                stopLocationUpdates();
                FireBaseAnalyticsUtils.init().send(EventIdUtils.COMPASS_LOCATION_FAILED);
            }

            @Override
            public void onLocationChanged(Location location) {
                stopLocationUpdates();
                updateLocation(location);
            }
        };
    }

    private void updateLocation(Location location) {
        if (location != null) {
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();

            // 将经纬度格式化为度分秒
            String[] formattedLatitude = convertToDMS(latitude, true);
            String[] formattedLongitude = convertToDMS(longitude, false);

            // 回调接口，将定位数据传递给其他地方
            locationCallback.onLocationReceived(formattedLatitude, formattedLongitude);
            FireBaseAnalyticsUtils.init().send(EventIdUtils.COMPASS_LOCATION_SUCCESS);
        } else {
            FireBaseAnalyticsUtils.init().send(EventIdUtils.COMPASS_LOCATION_FAILED);
            // 定位失败，也需要释放监听
            stopLocationUpdates();
        }
    }

    // 将经纬度格式化为度分秒
    private String[] convertToDMS(double value, boolean isLatitude) {
        int degrees = (int) value;
        value = (value - degrees) * 60;
        int minutes = (int) value;
        value = (value - minutes) * 60;
        double seconds = value;

        String direction = isLatitude ? (value < 0 ? "南纬" : "北纬") : (value < 0 ? "西经" : "东经");

        DecimalFormat decimalFormat = new DecimalFormat("00");
        return new String[]{direction,  degrees + "°" + decimalFormat.format(minutes) + "′" + decimalFormat.format(seconds) + "″"};
    }

    public interface LocationCallback {
        void onLocationReceived(String[] latitude, String[] longitude);
    }
}