98 lines
3.1 KiB
Swift
98 lines
3.1 KiB
Swift
import Foundation
|
|
import RealmSwift
|
|
import RxSwift
|
|
import CoreLocation
|
|
|
|
public class VehicleEvent: Object, Codable, Cloneable {
|
|
@Persisted public var id: String = UUID().uuidString
|
|
@Persisted public var date: TimeInterval = Date().timeIntervalSince1970
|
|
@Persisted public var latitude: Double = 0
|
|
@Persisted public var longitude: Double = 0
|
|
@Persisted public var address: String? = nil
|
|
@Persisted public var addedBy: String? = nil
|
|
|
|
public var number: String?
|
|
public var coordinate: CLLocationCoordinate2D {
|
|
return CLLocationCoordinate2D(latitude: self.latitude, longitude: self.longitude)
|
|
}
|
|
|
|
public init(lat: Double, lon: Double) {
|
|
self.latitude = lat
|
|
self.longitude = lon
|
|
self.addedBy = Settings.shared.user.email
|
|
}
|
|
|
|
required override init() {
|
|
super.init()
|
|
}
|
|
|
|
public func findAddress() -> Single<Void> {
|
|
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.address = copy.address
|
|
self.number = copy.number
|
|
self.addedBy = copy.addedBy
|
|
}
|
|
|
|
// MARK: - Codable
|
|
|
|
enum CodingKeys: String, CodingKey {
|
|
case id, date, latitude, longitude, address, addedBy
|
|
}
|
|
|
|
public func encode(to encoder: Encoder) throws {
|
|
var container = encoder.container(keyedBy: CodingKeys.self)
|
|
try container.encode(id, forKey: .id)
|
|
try container.encode(date, forKey: .date)
|
|
try container.encode(latitude, forKey: .latitude)
|
|
try container.encode(longitude, forKey: .longitude)
|
|
try container.encodeIfPresent(address, forKey: .address)
|
|
try container.encodeIfPresent(addedBy, forKey: .addedBy)
|
|
}
|
|
}
|