
import Foundation
import Alamofire

public protocol Request {

    var path: String { get }
    var method: HTTPMethod { get }
    var parameters: [String: Any] { get set }
    
    associatedtype Response: Parsable
}

public enum AlamofireError: Error {
    case jsonMapping
    case errorCode
    case connectionFaild
}

protocol Client {
    
    var host: String { get }
    
    func config(handler: @escaping (Config?) -> ())
}


struct AlamofireClient: Client {
    
    let host = "http://common.yhlongtime.top/"
    let key = "Q8bkWigT"

    
    func config(handler: @escaping (Config?) -> ()) {
        let urlString = "https://common.yhlongtime.top/pubv3/cSearchConfig.php"
        let url = URL(string: urlString)!
     
        let headers:HTTPHeaders = ["Content-type":"application/x-www-form-urlencoded",
                                   "Accept":"application/json"]
        
        
        AF.request(url, method: .post, parameters: ["user_pkname":"com.yhgc.Toolboxes"], headers: headers )
            .responseString { (response) in
                if  response.value == nil{
                    return
                }
                if let json = response.value?.decrypt,
                   let decryptedData = json.data(using: .utf8) {
                 
                    let jsonString = String(data: decryptedData, encoding: .utf8)
                    
                    switch response.result {
                    case .success:
                        if jsonString == nil {
                            handler(nil)
                            return
                        }
                        if let jsonData = jsonString!.data(using: .utf8) {
                            do {
                                if let dictionary = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
                                    print("\n---------config dictionary---------\n\(dictionary)")
                                    // 使用Config的parse方法解析
                                    if let config = Config.parse(json: dictionary) {
                                        handler(config)
                                    } else {
                                        handler(nil)
                                    }
                                } else {
                                    handler(nil)
                                }
                            } catch {
                                print("解析错误:", error)
               
                                handler(nil)
                            }
                        } else {
                            handler(nil)
                        }
        
                    case .failure:
                        handler(nil)
                    }
                    return
                }
               
              
            }
    }
  
}
