//
//  MP_LocationManager.swift
//  MusicPlayer
//
//  Created by Mr.Zhou on 2024/4/23.
//

import Foundation
import CoreLocation

class MP_LocationManager: NSObject {
    static let shared = MP_LocationManager()
    var getAuthHandle: ((_ success: Bool) -> Void)?
    //位置管理
    private var locationManager: CLLocationManager!
    //定位信息（字符串）
    private var location:String = "US"
    override init() {
        super.init()
        locationManager = CLLocationManager()
        //设置了精度最差的 3公里内 kCLLocationAccuracyThreeKilometers
        locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
        locationManager.delegate = self
        
    }
    
    /// 获取定位权限并处理新事件
    /// - Parameter complete: 尾随事件
    func setLocationPermission(_ viewController:UIViewController ,complete:(() -> Void)?) {
        if MP_LocationManager().hasLocationPermission() == true {
            //成功获取权限
            if complete != nil {
                complete!()
            }
        }else {
            //未获取权限
            switch MP_LocationManager().locationPermission() {
            case .notDetermined:
                MP_LocationManager().requestLocationAuthorizaiton()
            case .restricted, .denied:
                DispatchQueue.main.async {
                    let alertController = UIAlertController(title: "Location permission request", message: "“Musicoo” needs to obtain your location information in order to refine the preview music information provided to you!", preferredStyle: .alert)
                    let CancelAction = UIAlertAction(title:"Cancel", style: .cancel)
                    let OKAction = UIAlertAction(title: "Settings", style: .default) { (action) in
                        let url = URL(string: UIApplication.openSettingsURLString)
                        if let url = url,UIApplication.shared.canOpenURL(url){
                            if #available(iOS 10, *) {
                                UIApplication.shared.open(url, options:[:], completionHandler: nil)
                            }else{
                                UIApplication.shared.canOpenURL(url)
                            }
                        }
                    }
                    alertController.addAction(CancelAction)
                    alertController.addAction(OKAction)
                    viewController.present(alertController, animated: true, completion: nil)
                }
            default:
                if complete != nil {
                    complete!()
                }
            }
        }
    }
    
    /// 设备是否开启了定位服务
    fileprivate func hasLocationService() -> Bool {
        
        return CLLocationManager.locationServicesEnabled()
        
    }
    /// APP是否有定位权限
    fileprivate func hasLocationPermission() -> Bool {
        
        switch locationPermission() {
        case .notDetermined, .restricted, .denied:
            return false
        case .authorizedWhenInUse, .authorizedAlways:
            return true
        default:
            break
        }
        return false
    }
    
    /// 定位的权限
    fileprivate func locationPermission() -> CLAuthorizationStatus {
        if #available(iOS 14.0, *) {
            let status: CLAuthorizationStatus = locationManager.authorizationStatus
            print("location authorizationStatus is \(status.rawValue)")
            return status
        } else {
            let status = CLLocationManager.authorizationStatus()
            print("location authorizationStatus is \(status.rawValue)")
            return status
        }
    }
    
    
    //MARK: - 获取权限，在代理‘didChangeAuthorization’中拿到结果
    func requestLocationAuthorizaiton() {
        locationManager.requestWhenInUseAuthorization()
        
    }
    //MARK: - 获取位置
    func requestLocation() -> String {
        //请求地理位置
        locationManager.requestLocation()
        return location
    }
}
extension MP_LocationManager: CLLocationManagerDelegate {
   //MARK: - ios 14.0 之前，获取权限结果的方法
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        handleChangedAuthorization()
    }
    
    //MARK: - ios 14.0，获取权限结果的方法
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        handleChangedAuthorization()
    }
    
    private func handleChangedAuthorization() {
        if let block = getAuthHandle, locationPermission() != .notDetermined {
            if hasLocationPermission() {
                block(true)
            } else {
                block(false)
            }
        }
    }
    //MARK: - 获取定位后的位置
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let loction = locations.last {
            //成功获取定位
            print("latitude: \(loction.coordinate.latitude)   longitude:\(loction.coordinate.longitude)")
            let geocoder = CLGeocoder()
            geocoder.reverseGeocodeLocation(loction) { (placemarks, error) in
                if let placemark = placemarks?.first {
                    //编码成功
                    if let area = placemark.administrativeArea, !area.isEmpty {
                        print("Area code: \(area)")
                        self.location = area
                    } else if let locality = placemark.locality, !locality.isEmpty {
                        print("Area code: \(locality)")
                        self.location = locality
                    } else if let country = placemark.country, !country.isEmpty {
                        print("Country code: \(country)")
                        self.location = country
                    }
                }
                if let error = error {
                    print("Reverse geocoding failure: \(error.localizedDescription)")
                    //编码失败，默认设置位置是US
                    self.location = "US"
                    return
                }
            }
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Reverse geocoding failure: \(error.localizedDescription)")
        //编码失败，默认设置位置是US
        self.location = "US"
    }
}
