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

import Foundation
import CoreLocation

class EcaTask {
    var sessionShipStatus = SessionShipStatus()
    var eca = SharingData.eca

    func start() {
        print(debug: "called")
        sessionShipStatus.RequestShipStatus(responseShipStatus)
    }

    /**
     * Eca通知
     */
    private func notificationEca(point: SwitchingEca) {
        let alertDB = AlertDB.OnlyOne
        var wernrec = WarnRecord(title:"Eca", body:"")

        wernrec = alertDB.GetAlertEcaPoint(point: point)
        let formatstr = wernrec.title
        wernrec.title = String(format: formatstr)

        let voicemanager = AlertManager.OnlyOne
        voicemanager.VocalizeAlert(alertrec: wernrec, identifier: .EcaSwitching)
    }

    func responseShipStatus(result: Result<Data, APIError>) {
        print(debug: "called")
        switch result {
        case .success(let resultData):
            let serverSession = ServerSession()
            let resjson = serverSession.fromJSON(resultData: resultData, resltType: ResShipStatus.self)
            if let res = resjson {
                SharingData.my.speed = res.speed
                SharingData.my.course = res.course
                SharingData.my.heading = res.heading
                SharingData.my.server = CLLocationCoordinate2D(latitude: res.lat, longitude: res.lon)
                SharingData.my.dataTime = res.dataTime      //2023-11-02T05:25:49.4362123Z

                if Preferences.LocationType == 1 {
                    SharingData.my.location = SharingData.my.server
                    checkEca()
                }
            }
        case .failure(let errorCode):
            print(debug: errorCode)
            break
        }
    }

    func checkEca() {
        let runningEca = eca.ecaArea.first(where: {(key, value) in value.isRunning == true})
        if var eca = runningEca?.value {
            if let location = SharingData.my.location {
                let distance = LocationCalculation.checkPolyline(objPos: eca.points, shipPos: location)

                if eca.swNotice >= Float(distance) && eca.status == EcaState.start {
                    notificationEca(point: SwitchingEca.Start)
                    eca.status = EcaState.noticePass
                }

                if eca.swStart >= Float(distance) && eca.status == EcaState.noticePass {
                    notificationEca(point: SwitchingEca.Notice)
                    eca.status = EcaState.startPass
                }

                if eca.swFinish >= Float(distance) && eca.status == EcaState.startPass {
                    notificationEca(point: SwitchingEca.Finish)
                    eca.status = EcaState.finishPass
                }

                if 0.0 <= Float(distance) && eca.status == EcaState.finishPass {
                    eca.status = EcaState.incomplete
                }
            }
        }
    }
}
