//
//  TSGeneratePosterOperation.swift
//  AIRingtone
//
//  Created by 100Years on 2025/3/24.
//
import Combine
import Alamofire
class TSGeneratePosterOperationQueue: TSGenerateBaseOperationQueue {
    static let shared:TSGeneratePosterOperationQueue = TSGeneratePosterOperationQueue()

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

class TSGeneratePosterOperation: TSGenerateBaseOperation , @unchecked Sendable{
    
    override var actionInfoDict:[String:Any]{
        return [
            "actionType":"image_create",
            "comments": "Success",
            "costTime":9,
            "createdTimestamp":1742183242,
            "id":2449,
            "percent":1,
            "request":"{\"prompt\": \"Traditional Chinese ink painting style phoenix soaring through misty mountain peaks, dynamic black brushstrokes with crimson accents on rice paper texture, Googie architecture space station, 1950s atomic age aesthetic, curved aluminum panels, starburst patterns, glass dome observatory --edge_threshold 0.5 --atomic_age_style 0.8 --chrome_reflection 1.2\", \"width\": 800, \"height\": 1440, \"countryCode\": \"FR\"}",
            "response": "{\"resultUrl\": \"https://be-aigc.s3-accelerate.amazonaws.com/4c946f78-b1e7-4ffe-ba18-fff26b10178c.png\"}",
            "status":"success"
        ]
    }
    var gennerateType:TSGennerateType = .poster


    override func replaceSaveInfoModel(model:TSActionInfoModel){
        model.uuid = uuid
        TSPosterHistory.replaceModel(oldID: currentActionInfoModel.id, newModel: model)
        currentActionInfoModel = model
        dePrint("TSPosterHistory.listModelArray.count=\(TSPosterHistory.listModelArray.count)")
        dePrint("model actionStatus 发出=\(model.actionStatus)")
        currentActionInfoModelChanged?(currentActionInfoModel)
    }

    //模拟数据
//    func creatPoster(oldModel:TSActionInfoModel? = nil,prompt:String,promptSort:String) {
//        if let model = oldModel {
//            currentActionInfoModel = model
//        }else {
//            currentActionInfoModel.id = Int.timestampInt()
//            currentActionInfoModel.request.prompt = prompt
//            currentActionInfoModel.request.promptSort = promptSort
//            currentActionInfoModel.actionStatus = .pending
//            currentActionInfoModel.status = "pending"
//        }
//        replaceSaveInfoModel(model: currentActionInfoModel)
//        
//        stateDatauPblished = (.start,currentActionInfoModel)
//        let time = 5.0
//        
//        for i in 0..<Int(time){
//            kDelayOnMainThread(Double(i)) {
//                let progress = Float(i)*10/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)
//            }
////            TSPosterHistory.dePrintAllModel()
//        }
//    }
    

    
    //width 和 height 必须是 32 的倍数
    func creatPoster(oldModel:TSActionInfoModel? = nil,prompt:String,promptSort:String) {
        initializeFirstCurrentActionInfoModel(oldModel: oldModel, prompt: prompt, promptSort: promptSort)
        
        generatingProgress = 0
        let postDict:[String : Any] = [
            "prompt":prompt,
            "width":textPicW,
            "height":textPicH
        ]
        creatRequest = TSNetworkShared.post(urlType: .textPicCreate,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)
        }
    }
    

    override func getGeneratingProgressText()->String{
        return "Working on your contact poster \(generatingProgress)% ..."
    }
    
    var textPicW:Int{
        return kTextPicW
    }
    
    var textPicH:Int{
        return kTextPicH
    }
}
