//
//  RealmDatasource.swift
//  Arabami Sat
//
//  Created by Nikola Anevski on 21.4.21.
//

import UIKit
import RealmSwift

class RealmManager: NSObject {
    
    static let shared = RealmManager()
    let realm = getRealm()
    
    //MARK: - Properties
    lazy var imageDetails: Results<LocalImageData> = {
        self.realm.objects(LocalImageData.self)
    }()
    
    //MARK: - Methods
    func add(localImageData: LocalImageData) {
        try! realm.write() {
            realm.add(localImageData)
        }
        self.imageDetails = self.realm.objects(LocalImageData.self)
    }
    
    func deleteImageData(documentID: String) {
        if let image = self.realm.object(ofType: LocalImageData.self, forPrimaryKey: documentID) {
            try! self.realm.write() {
                self.realm.delete(image)
            }
            self.imageDetails = self.realm.objects(LocalImageData.self)
        }
    }
    
    func getImageData(documentID: String) -> LocalImageData? {
        return self.realm.object(ofType: LocalImageData.self, forPrimaryKey: documentID)
    }
    
    func emptyDatabase() {
        try! realm.write {
            realm.deleteAll()
        }
    }
    
    class func getRealm() -> Realm {
        if let _ = NSClassFromString("XCTest") {
            Realm.Configuration.defaultConfiguration.inMemoryIdentifier = NSUUID().uuidString
        }
        return try! Realm();
    }
}
