//
//  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() -> (alert: Bool, type: AlertType) {
        var alert = false
        let type: AlertType = .gpsPermission

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

        let status = CLLocationManager().authorizationStatus
        switch status {
        case .authorizedAlways :
            print(debug: "authorizationStatus : .authorizedAlways")
        case .notDetermined:
            alert = true
            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 = 1                      //1mぐらい移動したら位置情報取得
            locationManager.pausesLocationUpdatesAutomatically = false
            locationManager.activityType = .otherNavigation
            locationManager.headingFilter = 10.0
            locationManager.headingOrientation = .portrait  // どこを0度とするか指定

            locationManager.startUpdatingLocation()
        }

        return(alert, type)
    }

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

    // エラーハンドル
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(debug: error.localizedDescription)
    }

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

            if Preferences.LocationType == 0 {
                ecaTask.checkEca()
            }
        }

        if Preferences.LocationType == 1 {
            let eca = EcaTask()
            eca.start()
            
            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
//    }
}
