//
//  SpeakEleCallAIViewCtr.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/8/4.
//

import UIKit
import AVFAudio

class SpeakFreeTalkCallViewCtr: SpeakEleBaseViewCtr {

    
    @IBOutlet weak var SpeakCamera: SpeakCameraView!
    
    @IBOutlet weak var SpeakName: UILabel!
    @IBOutlet weak var SpeakCallTime: UILabel!
    @IBOutlet weak var SpeakCallIcon: UIImageView!
    
    @IBOutlet weak var SpeakAskWaitL: UILabel!
    
    @IBOutlet weak var SpeakAskT: UIButton!
    @IBOutlet weak var SpeakAskContentV: UIStackView!
    
    @IBOutlet weak var SpeakLastMsg: UIView!
    @IBOutlet weak var SpeakLastMsgDescp: UILabel!
    
    @IBOutlet weak var SpeakDisplayV: UIStackView!
    @IBOutlet weak var SpeakAskAgainV: UIStackView!
    
    @IBOutlet weak var SpeakEleLoadingView: SpeakEleLoading!
    
    @IBOutlet weak var SpeakVideoBtn: UIButton!
    @IBOutlet weak var SpeakSoundBtn: UIButton!
    
    @IBOutlet weak var SpeakAISer: UIView!
    
    private var viewModel = SpeakHomeViewModel()
    private var netViewModel:SpeakFreeTalkViewModel!
    private var dataSource:[SpeakFreeTalkModel] = []
    
    private var startTime = 0
    var isMate = false
    private var SpeakText = ""
    
    var isRecord = false {
        didSet {
            SpeakEleLoadingView.isHidden = !isRecord
            self.SpeakEleLoadingView.startAnimating()
            if isRecord {
                do {
                    try SpeakAudioToTextConverter.share.startRecording()
                }catch{ }
            }else{
                SpeakAudioToTextConverter.share.stopRecording()
            }
        }
    }
    
    private var studyTime = 0
    private var offset:Int = 0 {
        didSet{
            let min = offset / 60
            let sec = offset % 60
            SpeakCallTime.text = String(format: "%02d:%02d", min,sec)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        SpeakCamera.isHidden = true
        SpeakCallTime.isHidden = true
        SpeakAskT.isHidden = true
        SpeakAskContentV.isHidden = true
        SpeakEleLoadingView.isHidden = true
        SpeakLastMsg.isHidden = true
        SpeakDisplayV.gesture(target: self, class: UITapGestureRecognizer.self, selector: #selector(SpeakDisplayTaps))
        SpeakAskAgainV.gesture(target: self, class: UITapGestureRecognizer.self, selector: #selector(SpeakAskAgain))
        
        offset = SpeakDayEveryManager.manager.SpeakDayData.studyFreeTm ?? 300
        studyTime = SpeakDayEveryManager.manager.SpeakDayData.studytime ?? 0
        
        netViewModel.freeTalkUpdate = {[weak self] data in
            if let data = data as? [SpeakFreeTalkModel]{
                self?.dataSource = data
            }else if let su = data as? Bool {
                if su && self?.SpeakAISer.isHidden == true {
                    self?.SpeakAskT.isHidden = false
                }
            }
        }
        SpeakAudioToTextConverter.share.onResult = { [weak self] text in
            Print(text)
            self?.SpeakText = text
            self?.startTime = 0
        }
        
        let dsts = SpeakAIVideoPlayManager.share
        dsts.removeFromSuperview()
        self.SpeakAISer.addSubview(dsts)
        
    }
        
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.view.layoutIfNeeded()
        SpeakAIVideoPlayManager.share.frame = SpeakAISer.bounds
    }
    
    override func SpeakUpdate() {
        if !IAPViewModel.share.isSubscribed {
            if offset <= 0 {
                offset = 0
                if SpeakAudioToTextConverter.share.isRunning {
                    isRecord = false
                }
            }else{
                offset -= 1
                studyTime += 1
            }
        }else{
            studyTime += 1
        }
        if isRecord {
            self.startTime += 1
            if self.startTime > 2 {
                isRecord = false
                if self.SpeakText.count > 0 {
                    do {
                        let audioSession = AVAudioSession.sharedInstance()
                        try audioSession.setCategory(.playback ,mode: AVAudioSession.Mode.spokenAudio , options: [.duckOthers,.allowBluetoothA2DP])
                        try audioSession.setActive(true)
                    }catch {}
                    SpeakAskT.isHidden = true
                    SpeakAskT.isSelected = false
                    netViewModel.sendMessage(self.SpeakText)
                }else{
                    SpeakAskT.isSelected = false
                }
                self.startTime = 0
                self.SpeakText = ""
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        titleView.isHidden = true
        SpeakSoundBtn.isSelected = isMate
        AudioPlayerManager.shared.isMute = isMate
        let aiser = viewModel.AIser()
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
        let idx = SpeakElePublicManager.share.PublicData.AIerIndex
        let icon = "img_" + (aiser[safe: idx]?.name.lowercased() ?? "")
        self.SpeakCallIcon.image = UIImage(named: icon)
        SpeakName.text = aiser[safe: idx]?.name
        do{
            let audioSession = AVAudioSession.sharedInstance()
            try audioSession.setCategory(.playAndRecord ,mode: AVAudioSession.Mode.spokenAudio , options: [.duckOthers,.allowBluetoothA2DP])
            try audioSession.setActive(true)
        }catch{ }
        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
            self.display.isPaused = false
            self.dataSource = self.netViewModel.freeTalkMsg
            self.Ask()
        }
    }

    private func Ask() -> Void {
        SpeakAskContentV.isHidden = false
        SpeakCallTime.isHidden = false
        SpeakCallIcon.isHidden = true
        SpeakAskWaitL.isHidden = true
        SpeakAISer.isHidden = false
        SpeakAIVideoPlayManager.share.PlayBg()
        if netViewModel.isSpeech {
            SpeakAskT.isHidden = false
        }
    }
    
    @IBAction func SpeakVideoTaps(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        if SpeakCamera.isHidden == true {
            SpeakPermission.checkCameraPermission(completion: {[weak self] su in
                if su {
                    self?.SpeakCamera.startCamera()
                    self?.SpeakCamera.isHidden = false
                }
            })
        }else{
            SpeakCamera.stopCamera()
            SpeakCamera.isHidden = true
        }
    }
    
    
    @IBAction func SpeakSpeakTaps(_ sender: Any) {
        SpeakAskT.isSelected = true
        isRecord = true
        SpeakAIVideoPlayManager.share.PlayBg()
    }
    
    
    @objc private func SpeakDisplayTaps() -> Void {
        let last = self.dataSource.last
        SpeakLastMsgDescp.text = last?.content
        SpeakLastMsg.isHidden = !SpeakLastMsg.isHidden
    }
    
    @objc private func SpeakAskAgain() -> Void {
        isRecord = false
        let speed = SpeakElePublicManager.share.PublicData.speed
        let last = self.dataSource.last
        if let audio = last?.video {
            let d = AudioPlayerManager.shared.setupAudioPlayer(with: audio ,isMuted: isMate)
            SpeakAIVideoPlayManager.share.PlaySpeak(d/speed)
        }else if let audio = SpeakCache.cache.loadData(fileName: "\(last?.recordId ?? 0)") {
            let d = AudioPlayerManager.shared.setupAudioPlayer(with: audio ,isMuted: isMate)
            SpeakAIVideoPlayManager.share.PlaySpeak(d/speed)
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        display.isPaused = true
        display.invalidate()
        AudioPlayerManager.shared.stop()
        SpeakAudioToTextConverter.share.stopRecording()
        
    }
    
    @IBAction func SpeakCloseTaps(_ sender: Any) {
        SpeakDayEveryManager.manager.SpeakDayData.studyFreeTm = self.offset
        SpeakDayEveryManager.manager.SpeakDayData.studytime = self.studyTime
        SpeakDayEveryManager.manager.update()
        if let call = self.view.callblack {
            call(isMate)
        }
        self.navigationController?.popViewController(animated: true)
    }
    
    
    @IBAction func SpeakSoundTaps(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        isMate = sender.isSelected
        AudioPlayerManager.shared.isMute = isMate
        AudioPlayerManager.shared.setVolume(isMate ? 0 : 1)
    }
    
    init(viewModel:SpeakFreeTalkViewModel?) {
        self.netViewModel = viewModel
        super.init(nibName: "SpeakEleCallAIViewCtr", bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        self.view.callblack = nil
    }
}
