import SwiftUI
import SwiftData
import SFSafeSymbols


private let df: DateFormatter = {
    let df = DateFormatter()
    df.dateStyle = .short
    df.timeStyle = .short
    return df
}()

struct HistoryListItem: View {

    let entry: HistoryItem

    var entryTime: String {
        df.string(from: entry.startDate)
    }

    var roundTripText: String {
        "\(Int(entry.roundTripTime * 1000)) ms"
    }
    
    var clientNonceText: String {
        "\(entry.message.clientChallenge)"
    }
    
    var serverNonceText: String {
        "\(entry.message.serverChallenge)"
    }
    
    var body: some View {
        VStack(alignment: .leading) {
            HStack {
                Image(systemSymbol: entry.route.symbol)
                Text(entry.response.description)
                    .font(.headline)
                Spacer()
                Text(entryTime)
            }
            HStack {
                Image(systemSymbol: .arrowUpArrowDownCircle)
                Text(roundTripText).padding(.trailing)
                Image(systemSymbol: .lockIphone)
                Text(clientNonceText).padding(.trailing)
                Image(systemSymbol: .doorRightHandClosed)
                Text(serverNonceText).padding(.trailing)
            }
            .foregroundColor(.secondary)
            .font(.footnote)
        }
    }
}

#Preview {
    do {
        let config = ModelConfiguration(isStoredInMemoryOnly: true)
        let container = try ModelContainer(for: HistoryItem.self, configurations: config)
        
        let item = HistoryItem.mock
        container.mainContext.insert(item)
        try container.mainContext.save()
        return HistoryListItem(entry: item)
            .modelContainer(container)
    } catch {
        fatalError("Failed to create model container.")
    }
}
