//
//  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.location.speed = res.speed
                SharingData.location.course = res.course
                SharingData.location.heading = res.heading
                SharingData.location.server = CLLocationCoordinate2D(latitude: res.lat, longitude: res.lon)
                SharingData.location.dataTime = res.dataTime      //2023-11-02T05:25:49.4362123Z

                SharingData.location.setLocation()
                print(debug: "Location:\(res)")
                checkEca()
            }
        case .failure(let errorCode):
            print(debug: errorCode)
            break
        }
    }

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

                    if 0.0 >= Float(distance) && SharingData.my.ecaStatus != EcaState.incomplete{
                        SharingData.my.ecaStatus = EcaState.incomplete
                        var newData = eca
                        newData.isRunning = false
                        newData.status = EcaState.incomplete
                        SharingData.eca.editEcaArea(key: eca.name, value: newData, type: EcaOperation.Incomplete)
                    }

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

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

                    if eca.swNotice >= Float(distance) && eca.swStart < Float(distance) && SharingData.my.ecaStatus != EcaState.noticePass{
                        notificationEca(point: SwitchingEca.Notice)
                        SharingData.eca.isShowEcaAlert = true
                        SharingData.my.ecaStatus = EcaState.noticePass
                    }
                }
            }
        } else {
            if SharingData.my.ecaStatus != nil {
                SharingData.my.ecaStatus = nil
            }
        }
    }

    func chengeEcaStatus(eca: RegisteredEca) {
        if let status = SharingData.my.ecaStatus{
            var newData = eca
            newData.status = status

            if status == EcaState.noticePass{     //ECA通知円到達
                SharingData.eca.editEcaArea(key: eca.name, value: newData, type: EcaOperation.Notice)
            }
            if status == EcaState.startPass{      //ECA開始円到達
                SharingData.eca.editEcaArea(key: eca.name, value: newData, type: EcaOperation.Start)
            }
            if status == EcaState.finishPass{     //ECAタスク終了円到達
                SharingData.eca.editEcaArea(key: eca.name, value: newData, type: EcaOperation.Finish)
            }
            if status == EcaState.end{            //ECAタスク完了（燃料切替実施済み)
                SharingData.eca.editEcaArea(key: eca.name, value: newData, type: EcaOperation.End)
            }
        }
    }

//    func checkEca() {
//        let runningEca = eca.ecaArea.first(where: {(key, value) in value.isRunning == true})
//        if var eca = runningEca?.value {
//            if let location = SharingData.location.location {
//                if let distance = LocationCalculation.checkPolyline(objPos: eca.points, shipPos: location) {
//
//                    //ECA実行時に状態を取得
//                    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.incomplete {
//                        SharingData.eca.isShowEcaAlert = true
//                        SharingData.my.ecaStatus = EcaState.incomplete
//                    }
//                }
//            }
//        } else {
//            if SharingData.my.ecaStatus != nil {
//                SharingData.my.ecaStatus = nil
//            }
//        }
//    }

//    func runningEcaStatus(eca: RegisteredEca, distance: Double) -> RegisteredEca {
//        var result = false
//        var newData = eca
//
//        newData.status = EcaState.running
//
//        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)
//        }
//    }
}
