package com.base.locationsharewhite.map

import android.annotation.SuppressLint
import android.content.Context
import android.location.Criteria
import android.location.Location
import android.location.LocationManager
import android.view.View
import com.base.locationsharewhite.utils.BitmapUtils.getBitmapDescriptorFromLayoutResId
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.LatLngBounds
import com.google.android.gms.maps.model.Marker
import com.google.android.gms.maps.model.MarkerOptions

object MapUtils {

    private val TAG = "MapUtils"


    @SuppressLint("MissingPermission")
    fun Context.getLatLngByLocationManager(): LatLng? {

        var latitude: Double = -1.0
        var longitude: Double = -1.0
        val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager?

        if (locationManager != null) {
            val provider: String? = locationManager.getBestProvider(Criteria(), true)
            if (provider != null) {
                val lastKnownLocation: Location? = locationManager.getLastKnownLocation(provider)
                latitude = lastKnownLocation?.latitude ?: -1.0//维度
                longitude = lastKnownLocation?.longitude ?: -1.0//经度
            }
        }
        return if (latitude == -1.0 || longitude == -1.0) {
            null
        } else {
            LatLng(latitude, longitude)
        }

    }


    /**
     * 添加view为Marker
     */
    fun GoogleMap.addLocationMarker(
        marker: View,
        latLng: LatLng,
        tittle: String = "",
    ): Marker? {
        val bitmapDescriptor = getBitmapDescriptorFromLayoutResId(marker)
        return addMarker(
            MarkerOptions()
                .icon(bitmapDescriptor)
                .position(latLng)
                .title(tittle)
        )
    }

    /**
     * 多个经纬度相机移动合适位置
     */
    fun GoogleMap.cameraMovePointsBounds(point1: LatLng, point2: LatLng, padding: Int) {
        // 创建包含两个点的边界
        val bounds = LatLngBounds.Builder().include(point1).include(point2).build()
        moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, padding))
    }


}