package uni.deepoil.com;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.location.LocationManager;
import android.os.Build;
import android.os.Looper;

import com.alibaba.fastjson.JSONObject;
import com.hjq.permissions.XXPermissions;

import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.feature.uniapp.common.UniModule;

/**
 * 定位插件
 * @author Berial
 * @since 2025-06-11
 */
public class LocationModule extends UniModule {

    @UniJSMethod(uiThread = true)
    public void getLocationInfo(UniJSCallback callback) {
        final Context context = mUniSDKInstance.getContext();
        String[] permissions = {
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION
        };
        if (XXPermissions.isGranted(context, permissions)) {
            requestLocation(context, callback);
        } else {
            XXPermissions.with(context)
                    .permission(permissions)
                    .request((perms, allGranted) -> {
                        System.out.println(perms);
                        System.out.println("allGranted: " + allGranted);
                        if (allGranted) {
                            requestLocation(context, callback);
                        } else {
                            JSONObject json = new JSONObject();
                            json.put("success", false);
                            json.put("msg", "location permission is denied");
                            callback.invoke(json);
                        }
                    });
        }
    }

    @SuppressLint("MissingPermission")
    private void requestLocation(Context context, UniJSCallback callback) {
        final LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        String provider;
        if (lm.isProviderEnabled(LocationManager.FUSED_PROVIDER)) {
            provider = "fused";
        } else {
            provider = LocationManager.GPS_PROVIDER;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            lm.getCurrentLocation(provider, null, context.getMainExecutor(), location -> {
                JSONObject json = new JSONObject();
                json.put("lat", location.getLatitude());
                json.put("lon", location.getLongitude());
                json.put("success", true);
                callback.invoke(json);
            });
        } else {
            lm.requestSingleUpdate(provider, location -> {
                JSONObject json = new JSONObject();
                json.put("lat", location.getLatitude());
                json.put("lon", location.getLongitude());
                json.put("success", true);
                callback.invoke(json);
            }, Looper.getMainLooper());
        }
    }
}
