import SwiftUI

struct SettingsView: View {

    @Binding
    var keyManager: KeyManagement
    
    @Binding
    var serverAddress: String
    
    @Binding
    var localAddress: String

    @Binding
    var isCompensatingDaylightTime: Bool
    
    @Binding
    var useLocalConnection: Bool
    
    var body: some View {
        NavigationView {
            ScrollView {
                VStack(alignment: .leading, spacing: 8) {
                    VStack(alignment: .leading) {
                        Text("Server address")
                            .bold()
                        TextField("Server address", text: $serverAddress)
                            .padding(.leading, 8)
                    }.padding(.vertical, 8)
                    VStack(alignment: .leading) {
                        Text("Local address")
                            .bold()
                        TextField("Local address", text: $localAddress)
                            .padding(.leading, 8)
                    }.padding(.vertical, 8)
                    Toggle(isOn: $useLocalConnection) {
                        Text("Use direct connection to device")
                    }
                    Text("Attempt to communicate directly with the device. This is useful if the server is unavailable. Requires a WiFi connection on the same network as the device.")
                        .font(.caption)
                        .foregroundColor(.secondary)
                    ForEach(KeyManagement.KeyType.allCases) { keyType in
                        SingleKeyView(
                            keyManager: $keyManager,
                            type: keyType)
                    }
                    Toggle(isOn: $isCompensatingDaylightTime) {
                        Text("Compensate daylight savings time")
                    }
                    Text("If the remote has daylight savings time wrongly set, then the time validation will fail. Use this option to send messages with adjusted timestamps. Warning: Incorrect use of this option will allow replay attacks.")
                        .font(.caption)
                        .foregroundColor(.secondary)
                }.padding()
            }.onDisappear {
                if !localAddress.hasSuffix("/") {
                    localAddress += "/"
                }
            }
            .navigationTitle("Settings")
        }
    }
}

struct SettingsView_Previews: PreviewProvider {
    static var previews: some View {
        SettingsView(
            keyManager: .constant(KeyManagement()),
            serverAddress: .constant("https://example.com"),
            localAddress: .constant("192.168.178.42"),
            isCompensatingDaylightTime: .constant(true),
            useLocalConnection: .constant(false))
    }
}
