import UIKit
import Eureka
import RxSwift
import CoreLocation

class LocationEditController: FormViewController {
    
    private let bag = DisposeBag()
    private var doneButton: UIBarButtonItem!
    
    var date = Date()
    var placemark: Placemark? = nil
    
    var onDone: ((VehicleEvent) -> Void)?

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneTapped(_:)))
        self.navigationItem.rightBarButtonItem = self.doneButton
        self.doneButton.isEnabled = false

        form +++ Section("")
        <<< DateTimeInlineRow(){
            $0.title = NSLocalizedString("Date and time", comment: "")
            $0.value = self.date
        }.onChange { row in
            if let newDate = row.value {
                self.date = newDate
                self.doneButton.isEnabled = true
            } else {
                self.doneButton.isEnabled = false
            }
        }
            
        <<< LocationRow() { row in
            row.title = NSLocalizedString("Location", comment: "")
            row.value = self.placemark
        }.onChange { row in
            if let newPlacemark = row.value {
                self.placemark = newPlacemark
                self.doneButton.isEnabled = true
            } else {
                self.doneButton.isEnabled = false
            }
        }
    }
    
    @objc func doneTapped(_ sender: UIBarButtonItem) {
        guard let placemark = self.placemark else { return }
        let event = VehicleEvent(lat: placemark.latitude, lon: placemark.longitude, speed: -1, dir: -1)
        event.date = self.date.timeIntervalSince1970
        if let address = placemark.address {
            event.address = address
        }
        self.onDone?(event)
    }
}
