

import RealmSwift

class FilterObject: Object{
 
    @objc dynamic var id: Int = 0
    @objc dynamic var order: Int = 0
    @objc dynamic var title: String = ""
    @objc dynamic var group: String = ""
    @objc dynamic var group_title: String = ""
    @objc dynamic var isMultiple: Bool = false
    
    override static func primaryKey() -> String? {
        return "id"
    }
    
}


extension FilterObject{
    
    static func isEnabled(module: String) -> Bool{
        if ModuleManager.isEnabled(module: module){
            return true
        }
        return false
    }
    
    func save() {
        if self.id > 0 {
            let module = self
            
            let realm = try! Realm()
            realm.beginWrite()
            realm.add(module, update: .all)
            try! realm.commitWrite()
            
        }
    }
    
    static func findById(id: Int) -> FilterObject? {
        
        let realm = try! Realm()
        let predicate = NSPredicate(format: "id = %@", (id))
        if let module = realm.objects(FilterObject.self).filter(predicate).first {
            return module
        }
        
        return nil
    }
    
    static func get1() -> Results<FilterObject> {
        let realm = try! Realm()
        return realm.objects(FilterObject.self).sorted(byKeyPath: "group",ascending: true)
    }
    
    static func getGrouped() -> [String: Results<FilterObject>] {
       
        var result: [String: Results<FilterObject>] = [:]
        var groups: [String] = []
        
        let data_list = FilterObject.get1()
        
       
        
        for item in data_list {
            groups.append(item.group)
        }
        
       
        let size = groups.count-1
        
        for index in 0...size {
            let realm = try! Realm()
            let predicate = NSPredicate(format: "group = %@", groups[index])
            let list = realm.objects(FilterObject.self).filter(predicate).sorted(byKeyPath: "order",ascending: true)
            result[groups[index]] = list
        }
        
        
        Utils.printDebug("\(result)")
        
       
        
        return result
    }
    
}



extension Array where Element:FilterObject {

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

}


struct FilterObjStruct{
 
    var id: Int = 0
    var order: Int = 0
    var title: String = ""
    var  group: String = ""
    var group_title: String = ""
    var isMultiple: Bool = false
    

}

