import Foundation
import SQLite
import HealthKit
import HealthDB

extension HealthDatabase {

    private static let databaseFileUrl = Bundle.main.url(forResource: "healthdb_secure", withExtension: "sqlite")

    static var mock: HealthDatabase {
        let bundleUrl = databaseFileUrl!
        let local = FileManager.default.documentDirectory.appendingPathComponent("db.sqlite")
        if !FileManager.default.fileExists(atPath: local.path) {
            try! FileManager.default.copyItem(at: bundleUrl, to: local)
        }
        return try! HealthDatabase(fileUrl: local)
    }

    static var empty: HealthDatabase {
        let store = try! HKDatabaseStore(database: Connection(.inMemory))
        try! store.createTables()
        return .init(wrapping: store)
    }
}

extension Database {

//    static var mock: Database {
//        return .init(store: .mock)
//    }

    static var empty: Database {

        do {
            let connection = try Connection(.inMemory)
            let store =  HKDatabaseStore(database: connection)
            try store.createTables()
            try store.insert(workout: .mock1)
            return .init(store: .init(wrapping: store))
        } catch {
            print(error)
            fatalError("Failed to create empty database: \(error)")
        }
    }
}
