//
//  AlertManager.swift
//  Sailassist
//
//  Created by 三浦薫巳 on 2023/11/19.
//

import Foundation
import UIKit
import AVFoundation

// 音声を扱うクラスのうち、アラートに関するもの
class AlertManager {
    // シングルトン宣言
    static let OnlyOne = AlertManager()
    private var player: AVAudioPlayer!     // ここでインスタンスを作ると例外発生

    var lastAlert: PushNotificationTypes.LocalPushIdentifier = .Reserve
    var lastSpeech: String = ""

    private init() {
        //とりあえず音源を仮で置いておく
        let soundpath = Bundle.main.bundleURL.appendingPathComponent("no_sound.mp3")
        do {
            player = try AVAudioPlayer(contentsOf: soundpath)
        } catch {
        }
    }

    // 無音を鳴らす
    func PlayNoSound( identifier : String ) {
        let content = "no_sound.mp3"
        lastSpeech = identifier
        let soundpath = Bundle.main.bundleURL.appendingPathComponent(content)
        do {
            if(player.isPlaying){
                print(debug: "SOUND Playing: \(content)")
                //再生中の音を止めてしてしまうので再生しない
            } else {
                player = try AVAudioPlayer(contentsOf: soundpath)
                player.play()
                print(debug: "SOUND Go play: \(content)")
            }
        } catch {
            lastSpeech = ""
            print(debug: "SOUND NoSound: \(content)")
            return
        }
    }

    // 音声だけ鳴らす
    func Speaking( identifier : String, content : String ) {
        lastSpeech = identifier
        // 音声を再生する
        let soundpath = Bundle.main.bundleURL.appendingPathComponent(content)
        do {
            player = try AVAudioPlayer(contentsOf: soundpath)
            player.play()
            print(debug: "SOUND Go play: \(content)")
        } catch {
            lastSpeech = ""
            print(debug: "SOUND NoSound: \(content)")
            return
        }
    }

    // 音声再生中止
    func CancelSpeak( identifier : String ) {
        if let alertPlayer = player {
            if alertPlayer.isPlaying == true {
                if lastSpeech == identifier {
                    alertPlayer.stop()
                }
            }
        }
        lastSpeech = ""
    }

    // 警報を鳴らす。引数の型定義はAlertDB.swift
    func VocalizeAlert( alertrec : WarnRecord ) {
        VocalizeAlert( alertrec: alertrec, identifier: .EcaSwitching)
    }

    func VocalizeAlert( alertrec : WarnRecord, identifier : PushNotificationTypes.LocalPushIdentifier ) {

        print(debug: "alertrec = \(alertrec)")
        // 警報を通知する
        let content = UNMutableNotificationContent()
        content.title = alertrec.title
        content.body  = alertrec.body
        /* 「通知」側の音声は、再生時間上限(10sec)の関係で無音とする
                    *  無音声ファイル(no_sound.mp3)は予め AppDelegateで ${App}/Library/Sounds にコピー済み
                    */
        content.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: "no_sound.mp3"))
        // 「通知」を発生させる
        let request = UNNotificationRequest( identifier: identifier.rawValue, content: content, trigger: nil )
        // let request = UNNotificationRequest( identifier: "ShipWarn", content: content, trigger: nil )
        UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

        lastAlert = identifier
        // 音声を再生する
        let soundpath = Bundle.main.bundleURL.appendingPathComponent(alertrec.soundName)
        do {
                player = try AVAudioPlayer(contentsOf: soundpath)
                player.play()
                print(debug: "SOUND Go play: \(alertrec.soundName)")
        } catch {
            lastAlert = .Reserve
            print(debug: "SOUND NoSound: \(alertrec.soundName)")
            return
        }
    }

    // 警報の再生を中断する
    func CancelAlert() {
        CancelAlert(identifier : .EcaSwitching )
    }

    // 警報の再生を中断する
    func CancelAlert( identifier : PushNotificationTypes.LocalPushIdentifier ) {
        if let alertPlayer = player {
            if alertPlayer.isPlaying == true {
                if lastAlert == identifier {
                    alertPlayer.stop()
                }
            }
        }
        lastAlert = .Reserve
    }
}
