import Foundation
import RealmSwift
import RxSwift
import CoreLocation

class VehicleEvent: Object, Codable, Cloneable {
    @objc dynamic var id: String?
    @objc dynamic var date: TimeInterval = Date().timeIntervalSince1970
    @objc dynamic var latitude: Double = 0
    @objc dynamic var longitude: Double = 0
    @objc dynamic var speed: Double = 0
    @objc dynamic var direction: Double = 0
    @objc dynamic var address: String? = nil
    
    var number: String?
    var coordinate: CLLocationCoordinate2D {
        return CLLocationCoordinate2D(latitude: self.latitude, longitude: self.longitude)
    }
    
    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()
    }
    
    func findAddress() -> Single<Void> {
        if address != nil {
            return Single.just(())
        } else {
            return LocationManager
                .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
                    }
                }
        }
    }
    
    override static func ignoredProperties() -> [String] {
        return ["plateNumber"]
    }
    
    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)
    }
    
    func getLocationString() -> String {
        let coordinates = "Lat: \(self.latitude), Lon: \(self.longitude)"
        if let addressString = self.address {
            return "\(addressString) (\(coordinates)"
        } else {
            return coordinates
        }
    }
    
    // MARK: - Cloneable
    
    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
    }
}
