//
//  ModuleConfig.swift
//  NearbyStoresPro
//
//  Created by DT Team  on 3/8/20.
//  Copyright © 2020 Amine. All rights reserved.
//

import UIKit
import RealmSwift



class SyncAppConfig: Object{
    
    @objc dynamic var id: Int = 0
    @objc dynamic var _key: String = ""
    @objc dynamic var _value: String = ""
    @objc dynamic var _type: String = ""
    
    override static func primaryKey() -> String? {
        return "id"
    }
    
}


extension SyncAppConfig{
    
    static func findById(id: String) -> SyncAppConfig? {
        
        let realm = try! Realm()
        let predicate = NSPredicate(format: "_key = %@", (id))
        if let config = realm.objects(SyncAppConfig.self).filter(predicate).first {
            return config
        }
        
        return nil
    }
    
}


extension SyncAppConfig{
    
    func getValue(defaultValue: Bool) -> Bool {
        
        if self._type == "boolean", let value = Bool(self._value){
            return value
        }
        
        return defaultValue
    }
    
    func getValue(defaultValue: Int) -> Int {
        
        if self._type == "int", let value = Int(self._value){
            return value
        }
        
        return defaultValue
    }
    
    func getValue(defaultValue: Double) -> Double {
        
        if self._type == "double", let value = Double(self._value){
            return value
        }
        
        return defaultValue
    }
    
    func getValue(defaultValue: Float) -> Float {
        
        if self._type == "float", let value = Float(self._value){
            return value
        }
        
        return defaultValue
    }
    
    func getValue(defaultValue: String) -> String {
        
        if self._type == "string"{
            return self._value
        }
        
        return defaultValue
    }
    
}


extension Array where Element:SyncAppConfig {

    func saveAll(){
        let modules: [SyncAppConfig] = self
            if modules.count > 0 {
                let realm = try! Realm()
                realm.beginWrite()
                realm.add(modules,update: .all)
                try! realm.commitWrite()
            }
    }
    

}

