import Foundation
import HealthDB

final class Database: ObservableObject {

    @Published
    var store: HealthDatabase? = nil

    @Published
    var file: DatabaseFile? = nil

    init(store: HealthDatabase? = nil) {
        self.store = store
    }

    @discardableResult
    func load(database: DatabaseFile) -> Bool {
        guard database != file else {
            print("Same database not loaded again")
            return true
        }
        close()
        do {
            let store = try HealthDatabase(fileUrl: database.url)
            DispatchQueue.main.async {
                self.store = store
                self.file = database
            }
            print("Opened database \(database.file)")
            return true
        } catch {
            print("Failed to load database: \(error)")
            return false
        }
    }

    func close() {
        DispatchQueue.main.async {
            //store.close()
            self.store = nil
            self.file = nil
        }
    }
}
