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

import UIKit

class ShowStatisticsViewController: UIViewController {

    private var resultTextView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white
        title = "统计信息"

        createUI()
        loadAndDisplayStatistics()
    }

    private func createUI() {
        resultTextView = UITextView(
            frame: CGRect(
                x: 0,
                y: 200,
                width: UIScreen.main.bounds.width,
                height: 200
            )
        )
        resultTextView.backgroundColor = UIColor.lightGray
        resultTextView.font = UIFont.systemFont(ofSize: 14)
        resultTextView.isEditable = false // 防止用户编辑
        view.addSubview(resultTextView)
    }

    private func loadAndDisplayStatistics() {
        // 调用 DNSResolver 单例获取请求报告信息
        guard let reportArray = DNSResolver.share().getRequestReportInfo(),
              let jsonString = arrayToJSONString(reportArray) else {
            resultTextView.text = "无法生成统计信息"
            return
        }

        resultTextView.text = jsonString
    }

    /// 将 NSArray 或 Swift Array 转为格式化 JSON 字符串（带缩进）
    /// - Parameter array: 数据数组
    /// - Returns: 格式化的 JSON 字符串，失败返回 nil
    private func arrayToJSONString(_ array: [Any]) -> String? {
        do {
            let jsonData = try JSONSerialization.data(
                withJSONObject: array,
                options: .prettyPrinted  // 美化输出，带缩进
            )
            return String(data: jsonData, encoding: .utf8)
        } catch {
            print("JSON 序列化失败: $error.localizedDescription)")
            return nil
        }
    }
}

