//
//  LocationViewModel.swift
//  Sailassist
//
//  Created by 三浦薫巳 on 2023/11/13.
//

import CoreLocation

class LocationViewModel: NSObject, ObservableObject, CLLocationManagerDelegate {
    @Published var authorizationStatus: CLAuthorizationStatus
    @Published var lastSeenLocation: CLLocation?

    private let locationManager: CLLocationManager
    let ecaTask = EcaTask()

    override init() {
        locationManager = CLLocationManager()
        authorizationStatus = locationManager.authorizationStatus

        super.init()
    }

    func requestPermission() {
        locationManager.requestAlwaysAuthorization()
        let status = CLLocationManager().authorizationStatus
        switch status {
        case .authorizedAlways :
            print(debug: "authorizationStatus : .authorizedAlways")
        case .notDetermined:
            print(debug: "authorizationStatus : .notDetermined")
        case .restricted:
            print(debug: "authorizationStatus : .restricted")
        case .denied:
            print(debug: "authorizationStatus : .denied")
        case .authorizedWhenInUse:
            print(debug: "authorizationStatus : .authorizedWhenInUse")
        @unknown default:
            print(debug: "authorizationStatus : Unknown")
        }

        if status == .authorizedAlways || status == .authorizedWhenInUse {
            locationManager.delegate = self
            locationManager.allowsBackgroundLocationUpdates = true  // バックグラウンド実行中も座標取得する場合、trueにする
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.distanceFilter = 10                    //10mぐらい移動したら位置情報取得
            locationManager.pausesLocationUpdatesAutomatically = false
            locationManager.activityType = .otherNavigation

            locationManager.startUpdatingLocation()
        }
    }

    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        authorizationStatus = manager.authorizationStatus
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let newLocation = locations.last {
            print(debug: "called")
            lastSeenLocation = newLocation
            let targetCoordinate : CLLocationCoordinate2D = lastSeenLocation!.coordinate
            SharingData.my.gps = targetCoordinate
            SharingData.my.setLocation()

            ecaTask.checkEca()
        }
    }

//    func filterLocation(_ location: CLLocation) -> Bool {
//        let intervalTime = -location.timestamp.timeIntervalSinceNow
//
//        if intervalTime > 10 {  //位置情報を取得してから10秒以上
//            return false
//        }
//
//        if location.horizontalAccuracy < 0 {    //水平方向の位置精度
//            return false
//        }
//
//        if location.horizontalAccuracy > 100 {  //水平方向の誤差が100m
//            return false
//        }
//
//        return true
//    }
}
