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

import Foundation

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

    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 = eca.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) {

                }
            }
        }
    }
}
