//
//  TSTextPicGennerateVM.swift
//  AIEmoji
//
//  Created by 100Years on 2025/2/20.
//

import Combine

class TSTextPicGennerateVM {
   
    @Published var stateDatauPblished:(TSProgressState,TSGenmojiModel?) = (TSProgressState.none,nil)
    var aiText:String = ""
    
    //width 和 height 必须是 32 的倍数
    func creatImageEmoji(text:String,width:Int = 384 ,height:Int = 832) {
        aiText = text
        let postDict:[String : Any] = [
            "prompt":text,
            "width":width,
            "height":height
        ]
        stateDatauPblished = (.start,nil)
        TSNetworkShared.post(urlType: .textPicCreate,parameters: postDict) { data,error in
            if let dataDict = data as? [String:Any] ,
               dataDict.safeInt(forKey: "code") == 200,
               let actionId = dataDict["actionId"] as? Int{
                self.getActionInfo(action_id:actionId)
            }else{
                self.stateDatauPblished = (.failed(error?.localizedDescription ?? ""),nil)
            }
        }
    }
    
    func getActionInfo(action_id:Int){
        TSNetworkShared.get(urlType: .actionInfo,parameters: ["action_id":action_id]) { data,error in
            if let result = kNetWorkResultSuccess(data: data) {
                if let genmojiModel = TSGenmojiModel(JSON: result) {
                    switch genmojiModel.actionStatus {
                    case .success:
                        TSToastShared.hideLoading()
                        self.stateDatauPblished = (.success(nil),genmojiModel)
                    case .failed:
                        self.stateDatauPblished = (.failed(kNetWorkMessage(data: data) ?? ""),nil)
                    default:
                        kDelayOnMainThread(1.0) {
                            self.getActionInfo(action_id: action_id)
                        }
                    }
                }
            }else{
                self.stateDatauPblished = (.failed(error?.localizedDescription ?? ""),nil)
            }
        }
    }
    
}
