//
//  TSGeneratePhotoOperation.swift
//  AIRingtone
//
//  Created by 100Years on 2025/3/24.
//
import Combine
import Alamofire
class TSGeneratePhotoOperationQueue: TSGenerateBaseOperationQueue {

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

class TSGeneratePhotoOperation: TSGenerateBaseOperation , @unchecked Sendable{
    override var actionInfoDict:[String:Any]{
        return [
            "actionType":"image_create",
            "comments": "Success",
            "costTime":7,
            "createdTimestamp":1742183588,
            "id":2450,
            "percent":1,
            "request":"{\"prompt\": \"Steampunk floating library with brass gears and clockwork mechanisms, leather-bound books flying through amber-lit fog, Victorian-era architecture blended with retro-futurism, retro anime cel-shading, 1980s Toei Animation style, bold black outlines, limited color palette (--color 1980s_anime), visible film grain --edge_threshold 0.4 --cel_shading 0.8, Retain the original stone size of the photo\", \"width\": 800, \"height\": 800, \"countryCode\": \"US\"}",
            "response":"{\"resultUrl\": \"https://be-aigc.s3-accelerate.amazonaws.com/8b7fcac9-c691-4c3a-b497-401204fad3e9.png\"}",
            "status":"success"
        ]
    }


    var gennerateType:TSGennerateType = .photo

    override func replaceSaveInfoModel(model:TSActionInfoModel){
        model.uuid = uuid
        TSPhotoHistory.replaceModel(oldID: currentActionInfoModel.id, newModel: model)
        currentActionInfoModel = model
        dePrint("TSPhotoHistory.listModelArray.count=\(TSPhotoHistory.listModelArray.count)")
        dePrint("model actionStatus 发出=\(model.actionStatus)")
        currentActionInfoModelChanged?(currentActionInfoModel)
    }
    
    override func handleGenerateSuccess() {
        kPurchaseToolShared.useOnceForFree(type: .photo)
    }
    
//    //模拟数据
//    func creatPhoto(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)
//            }
////            TSPhotoHistory.dePrintAllModel()
//        }
//    }
    

    
    //width 和 height 必须是 32 的倍数
    func creatPhoto(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 Photo \(generatingProgress)% ..."
    }

    var textPicW:Int{
        return kTextPicW
    }
    
    var textPicH:Int{
        return kTextPicW
    }
}
