//
//  LocationManager.swift
//  Padel Tournament
//
//  Created by Razmig Sarkissian on 02/09/2023.
//

import Foundation
import CoreLocation

class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
    let manager = CLLocationManager()

    @Published var location: CLLocation?
    @Published var city: String?
    @Published var postalCode: String?
    @Published var requestStarted: Bool = false
    @Published var userReadableCityOrZipcode: String = ""
    @Published var lastError: Error? = nil
    
    override init() {
        super.init()
        manager.delegate = self
    }

    func requestLocation() {
        lastError = nil
        manager.requestLocation()
        requestStarted = true
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        location = locations.first
        location?.geocode(completion: { placemark, error in
            self.city = placemark?.first?.locality
            self.postalCode = placemark?.first?.postalCode
            self.requestStarted = false
        })
    }
    
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        if manager.authorizationStatus == .authorizedWhenInUse || manager.authorizationStatus == .authorizedAlways {
            DispatchQueue.main.async {
                self.requestLocation()
            }
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("locationManager didFailWithError", error)
        requestStarted = false
        self.lastError = error
    }
    
    func geocodeCity(cityOrZipcode: String, completion: @escaping (_ placemark: [CLPlacemark]?, _ error: Error?) -> Void) {
        CLGeocoder().geocodeAddressString(cityOrZipcode, completionHandler: completion)
    }
}

extension CLLocation {
    func geocode(completion: @escaping (_ placemark: [CLPlacemark]?, _ error: Error?) -> Void) {
        CLGeocoder().reverseGeocodeLocation(self, completionHandler: completion)
    }
}
