//
//  Untitled.swift
//  AIEmoji
//
//  Created by 100Years on 2025/1/17.
//

import Combine
import Alamofire
enum TSProgressState  {
    case none
    case start
    case pending
    case progress(CGFloat)
    case success(Any?)
    case failed(String)

}

class TSGenmojiGennerateViewModel {

    var creatRequest:DataRequest?
    var queryRequest:DataRequest?
    var stopNetwork = false
    
    @Published var stateDatauPblished:(TSProgressState,TSGenmojiModel?) = (TSProgressState.none,nil)
    var aiText:String = ""
    
    func creatImageEmoji(text:String) {
        stopNetwork = false
        aiText = text
        stateDatauPblished = (.start,nil)
        creatRequest = TSNetworkShared.post(urlType: .imageEmoji,parameters: ["prompt":text]) { [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
    }
    
}


