//
//  TSGeneralRintoneVM.swift
//  AIRingtone
//
//  Created by 100Years on 2025/3/6.
//

import Combine
import Alamofire

let actionInfoDict:[String:Any] = [
    "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"
]

class TSGeneralRintoneVM {

    var creatRequest:Request?
    var queryRequest:Request?
    var stopNetwork = false
   
    @Published var stateDatauPblished:(TSProgressState,TSActionInfoModel?) = (TSProgressState.none,nil)
    var aiText:String = ""
    var generatingProgress = 0
    //模拟数据
    func creatRintone(text:String) {

        stateDatauPblished = (.start,nil)
        stateDatauPblished = (.progressString(generating(progress: 0.0)),nil)

        kDelayOnMainThread(0.2) {
            self.stateDatauPblished = (.progressString(self.generating(progress: 0.5)),nil)
        }

        kDelayOnMainThread(1.0) {
            if Bool.random() {
                let infoModel = TSActionInfoModel(JSON: actionInfoDict)
                self.stateDatauPblished = (.success(nil),infoModel)
            }else{
                self.stateDatauPblished = (.failed("error?.localizedDescription"),nil)
            }
        }
    }
    
 
//    func creatRintone(text:String) {
//        generatingProgress = 0
//        aiText = text
//        let postDict:[String : Any] = [
//            "prompt":text,
//            "duration":20
//        ]
//        stateDatauPblished = (.start,nil)
//        stateDatauPblished = (.progressString(generating(progress: 0.0)),nil)
//        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)
//                }
//            }else{
//                self.stateDatauPblished = (.failed(error?.localizedDescription ?? ""),nil)
//            }
//        }
//    }
    
    func getActionInfo(action_id:Int){
        queryRequest = TSNetworkShared.get(urlType: .actionInfo,parameters: ["action_id":action_id]) { [weak self] data,error in
            guard let self = self else { return }
            if let result = kNetWorkResultSuccess(data: data) {
                if let genmojiModel = TSActionInfoModel(JSON: result) {
                    switch genmojiModel.actionStatus {
                    case .success:
                        TSToastShared.hideLoading()
                        self.stateDatauPblished = (.success(nil),genmojiModel)
                        generatingProgress = 0
                    case .failed:
                        self.stateDatauPblished = (.failed(kNetWorkMessage(data: data) ?? ""),nil)
                        generatingProgress = 0
                    default:
                        stateDatauPblished = (.progressString(generating(progress: genmojiModel.percent)),nil)
                        if stopNetwork == false {
                            kDelayOnMainThread(1.0) {
                                self.getActionInfo(action_id: action_id)
                            }
                        }
                    }
                }
            }else{
                self.stateDatauPblished = (.failed(error?.localizedDescription ?? ""),nil)
            }
        }
    }
    
    func cancelAllRequest(){
        creatRequest?.cancel()
        queryRequest?.cancel()
        stopNetwork = true
    }
    
    func generating(progress:Float) -> String {

        //Generating 0%-100%
        var progressInt = Int(progress*100)

        if generatingProgress >= progressInt{
            return "Generating \(generatingProgress)%"
        }

        if progressInt > 99 {
            progressInt = 99
        }
        
        generatingProgress = progressInt
        return "Generating \(progressInt)%"
    }
}
