//
//  SHLocationManager.swift
//  ShorthandMaster
//
//  Created by 明津李 on 2020/8/27.
//  Copyright © 2020 明津李. All rights reserved.
//

import UIKit
import CoreLocation

class SHLocationManager: NSObject, CLLocationManagerDelegate{
    
    static let shared = SHLocationManager()
    
    private override init() {}
    
    private lazy var locationManager: CLLocationManager = {
        let locationManager = CLLocationManager.init()
        locationManager.delegate = self
        locationManager.distanceFilter = kCLDistanceFilterNone
        locationManager.desiredAccuracy = kCLLocationAccuracyBest;
//        locationManager.allowsBackgroundLocationUpdates = true;
        return locationManager
    }()
    
    typealias locationHandler = ((String)->Void)
    var addressHandler: locationHandler?
    
    func locationStatusService(_ handler:@escaping locationHandler){
        addressHandler = handler
        if CLLocationManager.locationServicesEnabled() == true{
            locationManager.startUpdatingLocation()
            switch CLLocationManager.authorizationStatus() {
            case .notDetermined:
                locationManager.requestWhenInUseAuthorization()
                break
            case .restricted:
                break
            case .denied:
                break
            case .authorizedAlways:
                break
            case .authorizedWhenInUse:
                break
            @unknown default:
                break
            }
            
        }else{
            self.addressHandler?("未知")
            //alert  setting location
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        
        if let location = locations.first {
            let geocoder = CLGeocoder.init()
            geocoder.reverseGeocodeLocation(location) { (placemarks, error) in
                
                if let placemark = placemarks?.first {
//                    var city = placemark.locality
//                    if city == nil {
//                        city = placemark.administrativeArea
//                    }
                    let address = (placemark.subLocality ?? "") + (placemark.thoroughfare ?? "") + (placemark.subThoroughfare ?? "")
                    self.addressHandler?(address)
                }else{
                    self.addressHandler?("未知")
                }
            }
        }else{
            self.addressHandler?("未知")
        }
        manager.stopUpdatingLocation()
    }
}
