import SwiftUI
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.requestDate)
    }

    var roundTripText: String? {
        guard let time = entry.roundTripTime else {
            return nil
        }
        return "\(Int(time * 1000)) ms"
    }

    var counterText: String {
        let sentCounter = entry.request.id
        let startText = "\(sentCounter)"
        guard let rCounter = entry.responseMessage?.id else {
            return startText
        }
        let diff = Int(rCounter) - Int(sentCounter)
        guard diff != 1 && diff != 0 else {
            return startText
        }
        return startText + " (\(diff))"
    }

    var timeOffsetText: String? {
        guard let offset = entry.clockOffset else {
            return nil
        }
        return "\(offset) s"
    }
    
    var body: some View {
        VStack(alignment: .leading) {
            HStack {
                Text(entry.response?.description ?? "")
                    .font(.headline)
                Spacer()
                Text(entryTime)
            }.padding(.bottom, 1)
            HStack {
                if let roundTripText {
                    Image(systemSymbol: entry.usedLocalConnection ? .wifi : .network)
                    //Image(systemSymbol: .arrowUpArrowDownCircle)
                    Text(roundTripText)
                        .font(.subheadline)
                }
                //Spacer()
                Image(systemSymbol: .personalhotspot)
                Text(counterText)
                    .font(.subheadline)
                if let timeOffsetText {
                    //Spacer()
                    Image(systemSymbol: .stopwatch)
                    Text(timeOffsetText)
                        .font(.subheadline)
                }
            }.foregroundColor(.secondary)
        }
        //.padding()
    }
}

struct HistoryListItem_Previews: PreviewProvider {
    static var previews: some View {
        HistoryListItem(entry: .mock)
    }
}
