//
//  FaceStatePromter.swift
//  Gengmei
//
//  Created by 刘鹿杰 on 2019/11/5.
//  Copyright © 2019 更美互动信息科技有限公司. All rights reserved.
//

import UIKit

enum FaceState {
    case initial
    case near
    case right
    case far
}

class FaceStatePromter {
    // 加载资源
    let initialSoundUrl = URL(fileURLWithPath: Bundle.main.path(forResource: "seeHor", ofType: "mp3")!)
    let nearerSoundUrl = URL(fileURLWithPath: Bundle.main.path(forResource: "beFar", ofType: "mp3")!)
    let fartherSoundUrl = URL(fileURLWithPath: Bundle.main.path(forResource: "beNear", ofType: "mp3")!)
    let rightSoundUrl = URL(fileURLWithPath: Bundle.main.path(forResource: "closeEye_du", ofType: "mp3")!)
    var duSound = URL(fileURLWithPath: Bundle.main.path(forResource: "duLoudly", ofType: "mp3")!)
    var initialAudioPlayer: AVAudioPlayer!
    
    init() {
        do {
            self.initialAudioPlayer = try AVAudioPlayer(contentsOf: self.initialSoundUrl)
            initialAudioPlayer.prepareToPlay()
        } catch {
            print("sound file not found")
        }
    }

    var cameraState = FaceState.initial
    
    var state = FaceState.initial {
        willSet {}
        didSet {
            switch state {
            case .initial:
                if UserDefaults.standard.bool(forKey: "noHumanVoice") == true { return }
                if cameraState == .initial  && initialAudioPlayer.isPlaying { return }
                do {
                    try  initialAudioPlayer = AVAudioPlayer(contentsOf: self.initialSoundUrl)
                } catch {print("sound file not found")}
                if !didSetHuman {
                    didSetHuman = true
                    if isEarPhone() {
                        if UserDefaults.standard.float(forKey: "humanVoice_earPhone") == 0.0 {
                            if AVAudioSession.sharedInstance().outputVolume > 0.5 || AVAudioSession.sharedInstance().outputVolume < 0.3 {
                                DaiVolume.setVolume(0.4)
                            }
                        } else {
                            DaiVolume.setVolume(UserDefaults.standard.float(forKey: "humanVoice_earPhone"))
                        }
                    } else if UserDefaults.standard.float(forKey: "humanVoice") == 0.0 {
                        if AVAudioSession.sharedInstance().outputVolume > 0.55 || AVAudioSession.sharedInstance().outputVolume < 0.75 {
                            switch UIDevice.current.modelName {
                            case "iPhone 7", "iPhone 7 Plus", "new One":
                                DaiVolume.setVolume(0.6)
                            default:
                                DaiVolume.setVolume(0.65)
                            }
                        }
                    } else {
                        // 进来时有值了  直接获取过来设置
                        DaiVolume.setVolume(UserDefaults.standard.float(forKey: "humanVoice"))
                    }
                }
                audioPlayVoice(facestate: .initial)
            case .near:
                if UserDefaults.standard.bool(forKey: "noHumanVoice") == true { return }
                if cameraState == .near && initialAudioPlayer.isPlaying { return }
                do {
                    try  initialAudioPlayer = AVAudioPlayer(contentsOf: self.nearerSoundUrl)
                } catch {}
                audioPlayVoice(facestate: .near)
            case .far:
                if UserDefaults.standard.bool(forKey: "noHumanVoice") == true { return }
                if cameraState == .far  && initialAudioPlayer.isPlaying {  return }
                do {
                    try  initialAudioPlayer = AVAudioPlayer(contentsOf: self.fartherSoundUrl)
                } catch {}
                audioPlayVoice(facestate: .far)
            case .right:
                if UserDefaults.standard.bool(forKey: "noHumanVoice") == true { return }
                if cameraState == .right  && initialAudioPlayer.isPlaying { return }
                if !didSetNoHumam {
                    didSetNoHumam = true
                    if UserDefaults.standard.bool(forKey: "noHumanVoice") {
                        if isEarPhone() {
                            if UserDefaults.standard.float(forKey: "duVoice_earPhone") == 0.0 {
                                DaiVolume.setVolume(0.4)
                            } else {
                                DaiVolume.setVolume(UserDefaults.standard.float(forKey: "duVoice_earPhone"))
                            }
                        } else if UserDefaults.standard.float(forKey: "duVoice") == 0.0 {
                            switch UIDevice.current.modelName {
                            case "iPhone 7", "iPhone 7 Plus", "new One":
                                DaiVolume.setVolume(0.6)
                            default:
                                DaiVolume.setVolume(0.65)
                            }
                        } else {
                            DaiVolume.setVolume(UserDefaults.standard.float(forKey: "duVoice"))
                        }
                    }
                }
                do {
                    if UserDefaults.standard.bool(forKey: "noHumanVoice") == false {
                        try  initialAudioPlayer = AVAudioPlayer(contentsOf: self.rightSoundUrl)
                    }
                } catch {}
                audioPlayVoice(facestate: .right)
            }
        }
    }
    
    // 播放声音
    func audioPlayVoice(facestate: FaceState) {
        if !initialAudioPlayer.isPlaying {
            cameraState = facestate
            initialAudioPlayer.prepareToPlay()
            self.initialAudioPlayer.play()
        }
    }
    
    // 停止音频播放
    func stopPlayVoice() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
            self.initialAudioPlayer.stop()
        }
    }
    
    // 判断用户是否带耳机了
    func isEarPhone() -> Bool {
        let route = AVAudioSession.sharedInstance().currentRoute
        for desc in route.outputs {
            if desc.portType == AVAudioSessionPortHeadphones {
                return true
            }
        }
        return false
    }
}
