
import SwiftUI
import Foundation
import AsyncDNSResolver

struct BlockedCount: View {

    @Environment(\.scenePhase)
    private var scenePhase

    @EnvironmentObject
    private var viewModel: ViewModel

    @State private var txtRecord: String = "…"

    private static let startIndex = 44

    private static let formatter: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal

        return formatter
    }()

    var body: some View {
        Text(txtRecord)
        .onAppear {
            fetchTxtRecord()
        }
        .onChange(of: viewModel.blocklist) { _ in
            fetchTxtRecord()
        }
        .onChange(of: scenePhase) { newPhase in
            if newPhase == .active {
                fetchTxtRecord()
            }
        }
    }

    private func fetchTxtRecord() {
        Task {
            do {
                let resolver = try AsyncDNSResolver()

                let records = try await resolver.queryTXT(name: "stats.invalid")

                let text = records.map { $0.txt }.joined()

                if let number = text.split(separator: " ").first,
                   let intValue = Int(number),
                   let formatted = Self.formatter.string(for: intValue)
                {
                    txtRecord = formatted
                }
                else {
                    txtRecord = NSLocalizedString("Error", comment: "")
                }
            }
            catch {
                txtRecord = NSLocalizedString("Error", comment: "")
            }
        }
    }
}

#Preview {
    BlockedCount()
        .environmentObject(ViewModel())
}
