//
//  SpeakDialogueViewModel.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/8/5.
//

import UIKit
import AVFAudio
import AVFoundation

class SpeakDialogueViewModel: NSObject {
    
    let net = SpeakNetHomeViewModel()
    let profileNet = SpeakEleProfileNetViewModel()
    var DialogLeasson:SpeakLessonDescpModel?
    var SpeakUpdate:((Any?)->Void) = { data in }
    
    var isSpeech:Bool = false {
        didSet{
            SpeakUpdate(isSpeech)
        }
    }
    
    var dialogLeassAsk:[SpeakDialogueModel] = [] {
        didSet{
            dialogLeassAsk = dialogLeassAsk.map({ data in
                if var s = data as? SpeakDialogueModel {
                    s.AniState = .ANone
                    return s
                }
                return data
            })
            if SpeakElePublicManager.share.PublicData.Smarttips {
                if let last = dialogLeassAsk.last ,
                   last.role == .AI {
                    dialogLeassAsk[dialogLeassAsk.count-1].AniState = .loading
                }
            }
            SpeakUpdate(dialogLeassAsk)
        }
    }
    
    var dialogueTalk:SpeakdialogueTalkModel?{
        didSet{
            if dialogLeassAsk.last?.role == .loading {
                dialogLeassAsk.removeLast()
            }
            if let last = dialogLeassAsk.last {
                if (dialogueTalk?.isLearningCompleted ?? false) && dialogueTalk?.firstLearnCompleted ?? false{
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                        let vc = SpeakDialogTipsPrcticeViewCtr()
                        vc.show()
                    }
                }
                let show:Bool = UserDefaults.standard.object(forKey: UnsafeRawUserDefaultsKey.UnsafeDialogReviewShow.rawValue) as? Bool ?? false
                if (dialogueTalk?.learnedVocabulary ?? 0) == 3 && show == false {
                    var iiiii = SpeakDialogueModel()
                    iiiii.role = .AIReview
                    iiiii.content = "Can you give me a score on the Apple Store"
                
                    var bbbbb = SpeakDialogueModel()
                    bbbbb.role = .review
                    dialogLeassAsk.append(contentsOf: [iiiii,bbbbb])
                    UserDefaults.standard.set(true, forKey: UnsafeRawUserDefaultsKey.UnsafeDialogReviewShow.rawValue)
                    UserDefaults.standard.synchronize()
                }
            }
            for var talk in dialogueTalk?.contentList ?? [] {
                talk.role = .AI
                talk.id = talk.recordId
                talk.isPractiseCompleted = dialogueTalk?.isPractiseCompleted
                talk.isLearningCompleted = dialogueTalk?.isLearningCompleted
                talk.firstLearnCompleted = dialogueTalk?.firstLearnCompleted
                talk.learnedVocabulary = dialogueTalk?.learnedVocabulary
                dialogLeassAsk.append(talk)
            }
            Print("Learn : \(dialogueTalk?.learnedVocabulary)")
            SpeakUpdate(dialogLeassAsk)
            SpeakUpdate(dialogueTalk)
        }
    }
    
    
    
    func fetchHistroy(leassonId:Int ,isReStart:Bool = false) -> Void {
        isSpeech = false
        if isReStart {
            self.AIAsk(lessonId: leassonId ,isReStart: isReStart ,userAnswer: "", isSub: true)
        }else{
            let db:[SpeakDialogueModel]? = SpeakCache.cache.LoadMode(state: .MessageCache, name: "\(leassonId)")
            self.dialogLeassAsk = db ?? []
            net.learnCourseHistoryRecordList(param: ["lessonId": leassonId]) { [weak self] (su, data:[SpeakDialogueModel]?) in
                if su {
                    self?.isSpeech = true
                    if (data?.count ?? 0) > 0 {
                        self?.dialogLeassAsk = data ?? []
                        SpeakCache.cache.SaveModel(cache: data, state: .MessageCache, name: "\(leassonId)")
                    }else{
                        self?.AIAsk(lessonId: leassonId ,isReStart: isReStart ,userAnswer: "", isSub: IAPViewModel.share.isSubscribed)
                    }
                }
            }
        }
    }
    
    
    func collect(id:Int, isCollect:Bool ) -> Void {
        profileNet.collect(param: ["businessId":id,"type":1 ,"isCollect":isCollect]) {[weak self] (success, data:SpeakNetBaseDeflutMode?) in
            if success {
                self?.DialogLeasson?.isCollect = isCollect
                self?.SpeakUpdate(data)
            }
        }
    }
    
    func AIAsk(lessonId:Int,
               isReStart:Bool = false,
               userAnswer:String = "",
               isSub:Bool = false ) -> Void {
        self.isSpeech = false
        let idx = SpeakElePublicManager.share.PublicData.AIerIndex
        let airs = SpeakHomeViewModel().AIser()[safe: idx]
        let vodioID = airs?.voiceId
        net.SpeakAILeasson(param: ["lessonId":lessonId,"isReStart":isReStart ,"userAnswer":userAnswer, "isSub":IAPViewModel.share.isSubscribed ,"voiceId":vodioID]) {[weak self] ( su ,data:SpeakdialogueTalkModel?) in
            if su {
                self?.isSpeech = true
                if  var setD = data,
                    let db = setD.contentList {
                    setD.contentList = db.map({ db in
                        var new = db
                        new.promptContent = setD.promptContent
                        return new
                    })
                    self?.dialogueTalk = setD
                }
            }
        }
    }
    
    func translate(msg:String ,complate:@escaping((String?)->Void)) -> Void {
        net.translate(param: ["message":msg]) { (su, data:String?) in
            if su {
                complate(data)
            }
        }
    }
    
}
