//
//  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()
        locationManager.delegate = self
        locationManager.activityType = .automotiveNavigation
        locationManager.distanceFilter = 100                    //100mぐらい移動したら位置情報取得
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.allowsBackgroundLocationUpdates = true  // バックグラウンド実行中も座標取得する場合、trueにする
        locationManager.pausesLocationUpdatesAutomatically = false
        locationManager.startUpdatingLocation()
    }

    func requestPermission() {
        locationManager.requestWhenInUseAuthorization()
        locationManager.requestAlwaysAuthorization() // バックグラウンド実行中も座標取得する場合はこちら
    }

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

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let newLocation = locations.last {
//            let isLocation = filterLocation(newLocation)
//            if isLocation {
               lastSeenLocation = locations.first
                let targetCoordinate : CLLocationCoordinate2D = lastSeenLocation!.coordinate
                SharingData.my.gps = targetCoordinate
                if Preferences.LocationType == 0 {
                    SharingData.my.location = SharingData.my.gps
                    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
    }
}
