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

import Combine

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

class TSGenmojiGennerateViewModel {
   
    @Published var stateDatauPblished:(TSProgressState,TSGenmojiModel?) = (TSProgressState.none,nil)
    var aiText:String = ""
    
    func creatImageEmoji(text:String) {
        aiText = text
        stateDatauPblished = (.start,nil)
        TSNetworkShared.post(urlType: .imageEmoji,parameters: ["prompt":text]) { 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(4.0) {
                            self.getActionInfo(action_id: action_id)
                        }
                    }
                }
            }else{
                self.stateDatauPblished = (.failed(error?.localizedDescription ?? ""),nil)
            }
        }
    }
    
}


