//
//  SNICurlViewController.swift
//  DNSResolverSwiftDemo
//
//  Created by issuser on 2025/9/2.
//

import UIKit
import Foundation
/**
 * 自定义 DNS 解析器，符合 PDNSCurlProtocolDNSResolver 协议
 */
class MyDNSResolver: NSObject, PDNSCurlProtocolDNSResolver {

    /// 静态方法：解析域名，返回逗号分隔的 IP 列表字符串
    /// - Parameter domain: 要解析的域名
    /// - Returns: 解析出的 IPv4 地址列表（以逗号拼接），失败则返回 nil（走 Local DNS）
    static func resolveDomain(_ domain: String) -> String? {
        guard let ips = DNSResolver.share().getIpv4ByCache(withDomain: domain, andExpiredIPEnabled: true),
              !ips.isEmpty else {
            return nil // 返回 nil 表示不拦截，走系统 DNS
        }
        return ips.joined(separator: ",")
    }
}

// MARK: - SNICurlViewController
class SNICurlViewController: UIViewController {

    @IBOutlet private weak var resultTextView: UITextView!
    private var session: URLSession!

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white
        title = "SNI+libcurl场景"

        createUI()
        setupSession()
        creatData()
    }

    private func createUI() {
        resultTextView = UITextView(frame: CGRect(x: 0,
                                                 y: 200,
                                                 width: UIScreen.main.bounds.width,
                                                 height: 200))
        resultTextView.backgroundColor = UIColor.lightGray
        view.addSubview(resultTextView)
    }

    private func setupSession() {
        // 方案一：使用共享会话并注册 curl protocol
        self.session = URLSession.shared
        
        // 注册自定义协议（基于 libcurl）
        PDNSCurlProtocol.register()
        
        // 开启调试日志
        PDNSCurlProtocol.setDebugLogEnabled(true)
        
        // 设置自定义 DNS 解析器
        PDNSCurlProtocol.setDNSResolver(MyDNSResolver.self)

        /*
         // 方案二：使用配置化的 session（可选）
         let config = URLSessionConfiguration.default
         PDNSCurlProtocol.setDebugLogEnabled(true)
         PDNSCurlProtocol.install(into: config)
         PDNSCurlProtocol.setDNSResolver(MyDNSResolver.self)
         self.session = URLSession(configuration: config, delegate: self, delegateQueue: .main)
         */
    }

    private func creatData() {
//        let urlString = "https://m.jtexpress.com.cn"
        let urlString = "https://www.douyin.com/"
        guard let url = URL(string: urlString) else { return }
        var request = URLRequest(url: url)

        // 设置网络性能指标监听（Metrics Observer）
        PDNSCurlProtocol.setMetricsObserverBlockFor(request as! NSMutableURLRequest) { request, success, error, nameLookUpTimeMS, connectTimeMs, appConnectTimeMs, preTransferTimeMs, startTransferTimeMs, totalTimeMs in
            print("""
            Network Metrics:
            Success: \(success)
            Error: \(error?.localizedDescription ?? "nil")
            DNS Lookup: \(String(format: "%.2f", nameLookUpTimeMS))ms
            Connect: \(String(format: "%.2f", connectTimeMs))ms
            App Connect: \(String(format: "%.2f", appConnectTimeMs))ms
            Pre-transfer: \(String(format: "%.2f", preTransferTimeMs))ms
            Start Transfer: \(String(format: "%.2f", startTransferTimeMs))ms
            Total: \(String(format: "%.2f", totalTimeMs))ms
            """)
        }

        // 创建 data task
        let dataTask = session.dataTask(with: request) { [weak self] data, response, error in
            DispatchQueue.main.async {
                if let error = error {
                    print("_________error: $error.localizedDescription)")
                } else if let data = data, let string = String(data: data, encoding: .utf8) {
                    print("_________response: $string)")
                    print("响应: $response.debugDescription)")
                    self?.resultTextView.text = string
                }
            }
        }

        dataTask.resume()
    }
}

