//
//  ModuleManager.swift
//  NSApplication1.8
//
//  Created by DT Team  on 5/20/20.
//  Copyright © 2020 Amine. All rights reserved.
//

import UIKit
import RealmSwift

class ModuleManager: Object{
    
    @objc dynamic var module: String = ""
    @objc dynamic var enabled: Int = 0
   
    override static func primaryKey() -> String? {
        return "module"
    }
    
}


extension ModuleManager {

    func save() {
        if self.module != "" {
            let module = self

            let realm = try! Realm()
            realm.beginWrite()
            realm.add(module,update: .all)
            try! realm.commitWrite()
            
        }
    }
    
    static func findById(module: String) -> ModuleManager? {
           
           let realm = try! Realm()
           
        let predicate = NSPredicate(format: "module = %@", module)
        
           if let m = realm.objects(ModuleManager.self).filter(predicate).first {
               return m
           }
           
           return nil
       }
    
    
    
    static func isEnabled(module: String) -> Bool {
        
        let realm = try! Realm()
        
     let predicate = NSPredicate(format: "module = %@", module)
     
        if let m = realm.objects(ModuleManager.self).filter(predicate).first {
            if m.enabled == 1{
                return true
            }
        }
       
        return false
        
    }
    

}


extension Array where Element:ModuleManager {

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

}
