package com.aaron.kakao.hospitalmapfortube.util

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationManager
import android.os.Build

/**
 * Created by aaron on 2020-03-30
 */

object LocationUtil {
    fun getCurrentLocation(context: Context): Location? {
        var location: Location? = null
        val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager?

        locationManager?.let {
            val isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
            val isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)

            if (!isGPSEnabled && !isNetworkEnabled) {
                location = null
            } else {
                val hasLocationPermission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                } else {
                    PackageManager.PERMISSION_GRANTED
                }

                if (hasLocationPermission == PackageManager.PERMISSION_GRANTED) {
                    location = if (isNetworkEnabled) {
                        locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
                    } else {
                        locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
                    }
                }
            }
        }
        return location
    }
}