//
//  Guest.swift
//  NearbyStores
//
//  Created by DT Team on 5/20/18.
//  Copyright © DT Team. All rights reserved.
//

import UIKit
import RealmSwift

class Guest: Object {


    @objc dynamic var id: Int = 0
    @objc dynamic var senderId: String = ""
    @objc dynamic var fcmId: String = ""
    @objc dynamic var lat: Double = 0
    @objc dynamic var lng: Double = 0
    @objc dynamic var currentLocation: Bool = true
    @objc dynamic var locName: String = "Current Location"
    @objc dynamic var last_activity: String = ""
    
    override static func primaryKey() -> String? {
        return "id"
    }
    
    
    
}

extension Guest{
    

    func getChoosenLocation() -> GuestLocation{
        
        
        let guest_picked_location_locName = LocalData.getValue(key: "guest_picked_location_locName",defaultValue: "Uknown")
        let guest_picked_location_locLat = LocalData.getValue(key: "guest_picked_location_locLat",defaultValue: 0.0)
        let guest_picked_location_locLng = LocalData.getValue(key: "guest_picked_location_locLng",defaultValue: 0.0)
        
    
        var loc = GuestLocation(lat: self.lat, lng: self.lng, locName: "Current Location".localized)
        
        if let guest_picked_location = LocalData.getValue(key: "guest_picked_location"), guest_picked_location == true{
            loc.lat = guest_picked_location_locLat!
            loc.lng = guest_picked_location_locLng!
            loc.locName = guest_picked_location_locName
        }
        

        return loc
    }
    
}

struct GuestLocation{
    var lat: Double
    var lng: Double
    var locName: String
}


extension Guest{
    
    
    static func getInstance() -> Guest? {
        
        let realm = try! Realm()
        let guest = realm.objects(Guest.self).first
        
        if let g = guest {
            return g
        }
        
        return nil
    }
    
    
    static func saveGuest(guest: Guest?) {
        
        if let g = guest {
            
            let realm = try! Realm()
            
            let guests = realm.objects(Guest.self)
    
            realm.beginWrite()
            realm.delete(guests)
            realm.add(g,update: .all)
            try! realm.commitWrite()
            
            LocalData.setValue(key: "guest_id", value: g.id)
            
        }
        
    }
    
    static func isStored() -> Bool {
        
        let realm = try! Realm()
        let guest = realm.objects(Guest.self).first
        
        if guest != nil {
            return true
        }
        
        return false
    }
    
    
}
