import Foundation import RealmSwift import RxSwift import CoreLocation public class VehicleEvent: Object, Codable, Cloneable { @objc public dynamic var id: String = UUID().uuidString @objc public dynamic var date: TimeInterval = Date().timeIntervalSince1970 @objc public dynamic var latitude: Double = 0 @objc public dynamic var longitude: Double = 0 @objc public dynamic var speed: Double = 0 @objc public dynamic var direction: Double = 0 @objc public dynamic var address: String? = nil public var number: String? public var coordinate: CLLocationCoordinate2D { return CLLocationCoordinate2D(latitude: self.latitude, longitude: self.longitude) } public init(lat: Double, lon: Double, speed: Double, dir: Double) { self.latitude = lat self.longitude = lon self.speed = speed self.direction = dir } required init() { super.init() } public func findAddress() -> Single { if address != nil { return Single.just(()) } else { return RxLocationManager .getAddressForLocation(latitude: self.latitude, longitude: self.longitude) .map { addr in if let realm = self.realm { try realm.write { self.address = addr } } else { self.address = addr } } } } public override static func primaryKey() -> String? { return "id" } public override static func ignoredProperties() -> [String] { return ["plateNumber"] } public func getMapLink() -> URL? { var urlString = "http://maps.apple.com/?sll=\(self.latitude),\(self.longitude)" if let address = self.address?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) { urlString = urlString + "&address=" + address } return URL(string: urlString) } public func getLocationString() -> String { let coordinates = "Lat: \(self.latitude), Lon: \(self.longitude)" if let addressString = self.address { return "\(addressString) (\(coordinates)" } else { return coordinates } } // MARK: - Cloneable public required init(copy: VehicleEvent) { self.id = copy.id self.date = copy.date self.latitude = copy.latitude self.longitude = copy.longitude self.speed = copy.speed self.direction = copy.direction self.address = copy.address self.number = copy.number } }