import Foundation

enum DBErr: String, Error {
    case noContainer = "No group url for database. Make sure that app group set correctly"
}

extension DBConnection {
    public static func mainDbURL() throws -> URL {
        guard let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.snikket.shared") else {
            throw DBErr.noContainer
        }
        return containerURL.appendingPathComponent("snikket_main.db")
    }

    public private(set) static var createIfNotExist: Bool = false

    public static func migrateToGroupIfNeeded() throws {
        let dbURL = try mainDbURL()

        if !FileManager.default.fileExists(atPath: dbURL.path) {
            let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
            let documentDirectory = paths[0]
            let path = documentDirectory.appending("/mobile_messenger1.db")
            if FileManager.default.fileExists(atPath: path) {
                try FileManager.default.moveItem(atPath: path, toPath: dbURL.path)
            }
        }

        createIfNotExist = true
    }

    public static func initialize(dbPath: String) throws -> DBConnection {
        let conn = try DBConnection(dbPath: dbPath)
        try? conn.execute("PRAGMA busy_timeout = 2")
        try DBSchemaManager(dbConnection: conn).upgradeSchema()
        return conn
    }
}
