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

import Foundation

class EcaTask {
    var sessionShipStatus = SessionShipStatus()
    var sharingData = SharingData.shared

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

    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?.latitude = res.lat
                SharingData.My.server?.longitude = res.lon
                SharingData.My.dataTime = res.dataTime      //2023-11-02T05:25:49.4362123Z
            }
            checkEca()
        case .failure(let errorCode):
            print(debug: errorCode)
            break
        }
    }

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

                if eca.swStart >= Float(distance) {

                }
                if eca.swNotice >= Float(distance) {

                }
                if eca.swFinish >= Float(distance) {

                }
            }
        }
    }
}
