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

                SharingData.my.setLocation()

                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 {
                if let distance = LocationCalculation.checkPolyline(objPos: eca.points, shipPos: location) {

                    //起動時に状態を設定
                    if SharingData.my.ecaStatus == nil {
                        eca = runningEcaStatus(eca: eca, distance: distance)
                    }

                    if eca.swNotice >= Float(distance) && eca.status == EcaState.running {
                        notificationEca(point: SwitchingEca.Notice)
                        SharingData.eca.isShowEcaAlert = true
                        SharingData.my.ecaStatus = EcaState.noticePass
                    }

                    if eca.swStart >= Float(distance) && eca.status == EcaState.noticePass {
                        notificationEca(point: SwitchingEca.Start)
                        SharingData.eca.isShowEcaAlert = true
                        SharingData.my.ecaStatus = EcaState.startPass
                    }

                    if eca.swFinish >= Float(distance) && 0.0 < Float(distance) && eca.status == EcaState.startPass {
                        notificationEca(point: SwitchingEca.Finish)
                        SharingData.eca.isShowEcaAlert = true
                        SharingData.my.ecaStatus = EcaState.finishPass
                    }

                    if 0.0 >= Float(distance) && eca.status == EcaState.startPass {
                        SharingData.eca.isShowEcaAlert = true
                        SharingData.my.ecaStatus = EcaState.incomplete
                    }
                }
            }
        } else {
            SharingData.my.ecaStatus = nil
        }
    }

    func runningEcaStatus(eca: RegisteredEca, distance: Double) -> RegisteredEca {
        var result = false
        var newData = eca
        if 0.0 >= Float(distance){
            newData.status = EcaState.incomplete
            result = true
        }

        if eca.swFinish >= Float(distance) && result == false{
            newData.status = EcaState.startPass
            result = true
        }

        if eca.swStart >= Float(distance) && result == false{
            newData.status = EcaState.noticePass
            result = true
        }

        if eca.swNotice >= Float(distance) && result == false{
            newData.status = EcaState.running
        }

        return newData
    }

    func chengeEcaStatus(eca: RegisteredEca) {
        if eca.status == EcaState.running {
            var newData = eca
            newData.status = EcaState.noticePass
            SharingData.eca.editEcaArea(key: eca.name, value: newData, type: EcaOperation.Notice)
        }

        if eca.status == EcaState.noticePass {
            var newData = eca
            newData.status = EcaState.startPass
            SharingData.eca.editEcaArea(key: eca.name, value: newData, type: EcaOperation.Start)
        }

        if eca.status == EcaState.startPass {
            var newData = eca
            newData.status = EcaState.finishPass
            SharingData.eca.editEcaArea(key: eca.name, value: newData, type: EcaOperation.Finish)
        }

        if eca.status == EcaState.finishPass {
            var newData = eca
            newData.status = EcaState.incomplete
            SharingData.eca.editEcaArea(key: eca.name, value: newData, type: EcaOperation.Incomplete)
        }
    }
}
