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

import CoreLocation

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

    private let locationManager: CLLocationManager
    let ecaTask = EcaTask()

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

        super.init()
    }

    func requestPermission() -> Bool {
        var alert = true

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

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

            locationManager.startUpdatingLocation()
        }

        return alert
    }

    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.location.gps = targetCoordinate
            SharingData.location.setLocation()

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

        if Preferences.LocationType == 1 {
            if serverLocationInterval <= DateTextLib.Date2UnixTime(date: Date()) {
                let eca = EcaTask()
                eca.start()

                self.ecaTask.checkEca()
                serverLocationInterval = DateTextLib.Date2UnixTime(date: Date()) + Int64(TimerInterval)
            }
        }
    }

//    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
//    }
}
