//
//  TSGenerateRintoneOperation.swift
//  AIRingtone
//
//  Created by 100Years on 2025/3/21.
//

import Combine
import Alamofire


class TSGenerateRintoneOperationQueue: TSGenerateBaseOperationQueue {
    static let shared:TSGenerateRintoneOperationQueue = TSGenerateRintoneOperationQueue()
    func creatOperation(uuid: String) -> TSGenerateRintoneOperation {
        let operation = super.creatOperation(uuid: uuid, type: TSGenerateRintoneOperation.self)
        handleStateDatauPblished(uuid: uuid, generateOperation: operation as! TSGenerateBaseOperation, notificationName: .kGenerateRintoneOperationChanged)
        return operation as! TSGenerateRintoneOperation
    }
    
    override func getUUIDData(uuid:String)->(TSProgressState,TSActionInfoModel?){
        if let rintoneOperation = TSGenerateRintoneOperationQueue.shared.findOperation(uuid: uuid) as? TSGenerateRintoneOperation {
            dePrint("TSBaseOperation stateDatauPblished 发送 = \(rintoneOperation.stateDatauPblished)")
            return (rintoneOperation.stateDatauPblished.0,rintoneOperation.currentActionInfoModel)
        }
        return (.none,TSActionInfoModel())
    }
    

}

class TSGenerateRintoneOperation: TSGenerateBaseOperation , @unchecked Sendable{
    
    override var actionInfoDict:[String:Any]{
        return [
            "actionType":"music_create",
            "comments": "Success",
            "costTime":15,
            "createdTimestamp":1741338454,
            "id":1536,
            "percent":1,
            "request":"{\"prompt\": \"Create a Techno ringtone with a repetitive bassline, crisp hi-hats, and subtle synth textures. Use a BPM of 125-130 for a sleek, modern sound., Create a uplifting and modern music track blending Pop, Electronic, and Ambient elements. Use a BPM of 100-120, a catchy melody with synth or piano, warm harmonies, and a mix of electronic and organic sounds. Ensure a clear structure (Intro, Verse, Chorus, Outro) and a light, positive vibe suitable for background or casual listening\", \"duration\": 5}",
            "response":"{\"coverUrl\": \"https://be-aigc.s3-accelerate.amazonaws.com/f0fb7739-a5cc-4805-9b68-b4a5890eb285.png\", \"title\": \"Neon Pulse\\\"  \\n\\\"Horizon Glow\", \"musicUrl\": \"https://be-aigc.s3-accelerate.amazonaws.com/c47d40dd-d07c-4edc-a6d9-8382438149d1.wav\"}",
            "status":"success"
        ]
    }
    
    override func replaceSaveInfoModel(model:TSActionInfoModel){
        model.uuid = uuid
        TSAIRintoneHistory.replaceModel(oldID: currentActionInfoModel.id, newModel: model)
        currentActionInfoModel = model
        dePrint("TSAIRintoneHistory.listModelArray.count=\(TSAIRintoneHistory.listModelArray.count)")
        dePrint("model actionStatus 发出=\(model.actionStatus)")
        currentActionInfoModelChanged?(currentActionInfoModel)
    }
    
    override func handleGenerateSuccess() {
        kPurchaseToolShared.useOnceForFree(type: .ringtones)
        let gennerateVC = TSGeneralRintoneVC(prompt:"",promptSort: "",showInfoModel: currentActionInfoModel){ model in }
        if let rootVC = WindowHelper.getCurrentViewController() {
            gennerateVC.modalPresentationStyle = .overFullScreen
            gennerateVC.modalTransitionStyle = .crossDissolve
            rootVC.present(gennerateVC, animated: true)
        }
    }
    

//    //模拟数据
//    func creatRintone(oldModel:TSActionInfoModel? = nil,prompt:String,promptSort:String) {
//        
//    initializeFirstCurrentActionInfoModel(oldModel: oldModel, prompt: prompt, promptSort: promptSort)
//        let time = 8.0
//        
//        for i in 0..<Int(time){
//            kDelayOnMainThread(Double(i)) {
//                let progress = Float(i)*10.0/100.0
//                self.currentActionInfoModel.percent = progress
//                self.currentActionInfoModel.actionStatus = .running
//                self.currentActionInfoModel.status = "running"
//                self.replaceSaveInfoModel(model: self.currentActionInfoModel)
//                self.stateDatauPblished = (.progressString(self.generating(progress: progress)),nil)
//            }
//        }
//
//        kDelayOnMainThread(time+1.0) {
//            if kRandomBool(), let infoModel = TSActionInfoModel(JSON: self.actionInfoDict){
//                infoModel.id = Int.uuid
//                self.replaceSaveInfoModel(model: infoModel)
//                self.stateDatauPblished = (.success(nil),self.currentActionInfoModel)
//            }else{
//                self.currentActionInfoModel.actionStatus = .failed
//                self.currentActionInfoModel.status = "failed"
//                self.replaceSaveInfoModel(model: self.currentActionInfoModel)
//                self.stateDatauPblished = (.failed("error?.localizedDescription"),nil)
//            }
//            TSAIRintoneHistory.dePrintAllModel()
//        }
//    }
    
    func creatRintone(oldModel:TSActionInfoModel? = nil,prompt:String,promptSort:String) {
        initializeFirstCurrentActionInfoModel(oldModel: oldModel, prompt: prompt, promptSort: promptSort)
       
       generatingProgress = 0
       let postDict:[String : Any] = [
           "prompt":prompt,
           "duration":20
       ]

       creatRequest = TSNetworkShared.post(urlType: .musicCreate,parameters: postDict) { [weak self] data,error in
           guard let self = self else { return }
           if let dataDict = data as? [String:Any] ,
              dataDict.safeInt(forKey: "code") == 200,
              let actionId = dataDict["actionId"] as? Int{
               if stopNetwork == false {
                   self.getActionInfo(action_id:actionId)
                   return
               }
           }
           
           handleFailInfoModel(errorString: error?.localizedDescription)
       }
   }

    
}
