//
//  SettingsView.swift
//  USB Meter
//
//  Created by Bogdan Timofte on 14/03/2020.
//  Copyright © 2020 Bogdan Timofte. All rights reserved.
//

import SwiftUI

struct MeterSettingsView: View {
    
    @EnvironmentObject private var meter: Meter
    
    @State private var editingName = false
    @State private var editingScreenTimeout = false
    @State private var editingScreenBrightness = false

    var body: some View {
        ScrollView {
            VStack (spacing: 14) {
                settingsCard(title: "Name", tint: meter.color) {
                    HStack {
                        Spacer()
                        if !editingName {
                            Text(meter.name)
                                .foregroundColor(.secondary)
                        }
                        ChevronView(rotate: $editingName)
                    }
                    if editingName {
                        EditNameView(editingName: $editingName, newName: meter.name)
                    }
                }

                if meter.operationalState == .dataIsAvailable {
                    settingsCard(title: "Device Info", tint: .blue) {
                        DeviceInfoRow(label: "Advertised Model", value: meter.modelString)
                        DeviceInfoRow(label: "Displayed Model", value: meter.deviceModelSummary)
                        DeviceInfoRow(label: "Working Voltage", value: meter.documentedWorkingVoltage)
                        DeviceInfoRow(label: "Temperature Unit", value: meter.temperatureUnitDescription)
                        if meter.modelNumber != 0 {
                            DeviceInfoRow(label: "Model Code", value: "\(meter.modelNumber)")
                        }
                        if !meter.firmwareVersion.isEmpty {
                            DeviceInfoRow(label: "Firmware", value: meter.firmwareVersion)
                        }
                        if meter.serialNumber != 0 {
                            DeviceInfoRow(label: "Serial", value: "\(meter.serialNumber)")
                        }
                        if meter.bootCount != 0 {
                            DeviceInfoRow(label: "Boot Count", value: "\(meter.bootCount)")
                        }
                    }
                }

                if meter.operationalState == .dataIsAvailable && meter.supportsManualTemperatureUnitSelection {
                    settingsCard(title: "Temperature Unit", tint: .orange) {
                        Text("TC66 reports temperature using the unit selected on the device. Keep this setting matched to the meter.")
                            .font(.footnote)
                            .foregroundColor(.secondary)
                        Picker("", selection: $meter.tc66TemperatureUnitPreference) {
                            ForEach(TemperatureUnitPreference.allCases) { unit in
                                Text(unit.title).tag(unit)
                            }
                        }
                        .pickerStyle(SegmentedPickerStyle())
                    }
                }

                if meter.operationalState == .dataIsAvailable && meter.supportsUMSettings {
                    settingsCard(title: "Screen Timeout", tint: .purple) {
                        HStack {
                            Spacer()
                            if !editingScreenTimeout {
                                Text(meter.screenTimeout != 0 ? "\(meter.screenTimeout) Minutes" : "Off")
                                    .foregroundColor(.secondary)
                            }
                            ChevronView(rotate: $editingScreenTimeout)
                        }
                        if editingScreenTimeout {
                            EditScreenTimeoutView()
                        }
                    }

                    settingsCard(title: "Screen Brightness", tint: .yellow) {
                        HStack {
                            Spacer()
                            if !editingScreenBrightness {
                                Text("\(meter.screenBrightness)")
                                    .foregroundColor(.secondary)
                            }
                            ChevronView(rotate: $editingScreenBrightness)
                        }
                        if editingScreenBrightness {
                            EditScreenBrightnessView()
                        }
                    }
                }
            }
            .padding()
        }
        .background(
            LinearGradient(
                colors: [meter.color.opacity(0.14), Color.clear],
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
            .ignoresSafeArea()
        )
        .navigationBarTitle("Meter Settings")
        .navigationBarItems( trailing: RSSIView( RSSI: meter.btSerial.RSSI ).frame( width: 24 ) )
    }

    private func settingsCard<Content: View>(
        title: String,
        tint: Color,
        @ViewBuilder content: () -> Content
    ) -> some View {
        VStack(alignment: .leading, spacing: 12) {
            Text(title)
                .font(.headline)
            content()
        }
        .padding(18)
        .meterCard(tint: tint, fillOpacity: 0.18, strokeOpacity: 0.24)
    }
}

private struct DeviceInfoRow: View {
    let label: String
    let value: String

    var body: some View {
        HStack {
            Text(label)
            Spacer()
            Text(value)
                .foregroundColor(.secondary)
                .multilineTextAlignment(.trailing)
        }
        .font(.footnote)
    }
}

struct EditNameView: View {
    
    @EnvironmentObject private var meter: Meter
    
    @Binding var editingName: Bool
    @State var newName: String
    
    var body: some View {
        TextField("Name", text: self.$newName, onCommit: {
            self.meter.name = self.newName
            self.editingName = false
        })
            .textFieldStyle(RoundedBorderTextFieldStyle())
            .lineLimit(1)
            .disableAutocorrection(true)
            .multilineTextAlignment(.center)
    }
}

struct EditScreenTimeoutView: View {
    
    @EnvironmentObject private var meter: Meter
    
    var body: some View {
        Picker("", selection: self.$meter.screenTimeout ) {
            Text("1").tag(1)
            Text("2").tag(2)
            Text("3").tag(3)
            Text("4").tag(4)
            Text("5").tag(5)
            Text("6").tag(6)
            Text("7").tag(7)
            Text("8").tag(8)
            Text("9").tag(9)
            Text("Off").tag(0)
        }
        .pickerStyle( SegmentedPickerStyle() )
    }
}

struct EditScreenBrightnessView: View {
    
    @EnvironmentObject private var meter: Meter
    
    var body: some View {
        Picker("", selection: self.$meter.screenBrightness ) {
            Text("0").tag(0)
            Text("1").tag(1)
            Text("2").tag(2)
            Text("3").tag(3)
            Text("4").tag(4)
            Text("5").tag(5)
        }
        .pickerStyle( SegmentedPickerStyle() )
    }
}
