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

import Combine
import Alamofire

let kTextPicW = 800.0
let kTextPicH = 1440.0
let kTextWHScale = kTextPicW/kTextPicH

class TSTextPicGennerateVM {
    
    var creatRequest:DataRequest?
    var queryRequest:DataRequest?
    var stopNetwork = false
   
    @Published var stateDatauPblished:(TSProgressState,TSGenmojiModel?) = (TSProgressState.none,nil)
    var aiText:String = ""
    
    //width 和 height 必须是 32 的倍数
    func creatImageEmoji(text:String,width:Int = Int(kTextPicW) ,height:Int = Int(kTextPicH)) {
        aiText = text
        let postDict:[String : Any] = [
            "prompt":text,
            "width":width,
            "height":height
        ]
        stateDatauPblished = (.start,nil)
        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)
                }
            }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 = 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:
                        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
    }
}
