//
//  NgaTask.swift
//  Sailassist
//
//  Created by 三浦薫巳 on 2024/06/11.
//

import Foundation

class NgaTask {
    var ngaData = SharingData.nga

    /**
     * Nga通知
     */
    private func notificationNga(point: SwitchingAlert, name: String) {
        let alertDB = AlertDB.OnlyOne
        var wernrec = WarnRecord(title:"NGA", body:"")

        wernrec = alertDB.GetAlertNgaPoint(point: point)
        let formatstr = wernrec.title + name
        wernrec.title = String(format: formatstr)

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

    func checkNga() {
        ngaData.ngaArea.forEach { nga in
            if nga.value.isRunning {
                if let location = SharingData.location.location {
                    var shipPos = LocationCalculation.AreaLatLon()
                    shipPos.NorthLat = location.latitude
                    shipPos.SouthLat = location.latitude
                    shipPos.EastLon = location.longitude
                    shipPos.WestLon = location.longitude
                    var areaPoints = nga.value.points
                    areaPoints.append(nga.value.points[0])
                    let isInside = LocationCalculation.checkBeset(objPos: areaPoints, minMax: shipPos, exceed180: false)
                    var area = nga.value
                    if isInside {
                        //通過中
                        area.passingCnt += 1
                        ngaData.editNgaArea(value: area, type: NgaOperation.Passing)
                        if area.passingCnt == 1 {
                            let areaName = nga.value.name
                            notificationNga(point: SwitchingAlert.NgaPassing, name: areaName)
                        }
                    } else {
                        if area.passingCnt > 0 {
                            //通過
                            area.passingCnt = 0
                            ngaData.editNgaArea(value: area, type: NgaOperation.Passing)
                        }
                    }
                }
            }
        }
    }
}
