import * as Comlink from 'comlink';
import { openWorkerDatabasePort, resolveWorkerDatabasePortFactory } from '../../../worker/db/open-worker-database.js';
import { AbstractWebSQLOpenFactory } from '../AbstractWebSQLOpenFactory.js';
import { WorkerWrappedAsyncDatabaseConnection } from '../WorkerWrappedAsyncDatabaseConnection.js';
import { DEFAULT_CACHE_SIZE_KB, TemporaryStorageOption } from '../web-sql-flags.js';
import { InternalWASQLiteDBAdapter } from './InternalWASQLiteDBAdapter.js';
import { WASQLiteVFS, WASqliteConnection } from './WASQLiteConnection.js';
/**
 * Opens a SQLite connection using WA-SQLite.
 */
export class WASQLiteOpenFactory extends AbstractWebSQLOpenFactory {
    constructor(options) {
        super(options);
        assertValidWASQLiteOpenFactoryOptions(options);
    }
    get waOptions() {
        // Cast to extended type
        return this.options;
    }
    openAdapter() {
        return new InternalWASQLiteDBAdapter({
            name: this.options.dbFilename,
            openConnection: () => this.openConnection(),
            debugMode: this.options.debugMode,
            logger: this.logger
        });
    }
    async openConnection() {
        const { enableMultiTabs, useWebWorker } = this.resolvedFlags;
        const { vfs = WASQLiteVFS.IDBBatchAtomicVFS, temporaryStorage = TemporaryStorageOption.MEMORY, cacheSizeKb = DEFAULT_CACHE_SIZE_KB, encryptionKey } = this.waOptions;
        if (!enableMultiTabs) {
            this.logger.warn('Multiple tabs are not enabled in this browser');
        }
        if (useWebWorker) {
            const optionsDbWorker = this.options.worker;
            const workerPort = typeof optionsDbWorker == 'function'
                ? resolveWorkerDatabasePortFactory(() => optionsDbWorker({
                    ...this.options,
                    temporaryStorage,
                    cacheSizeKb,
                    flags: this.resolvedFlags,
                    encryptionKey
                }))
                : openWorkerDatabasePort(this.options.dbFilename, enableMultiTabs, optionsDbWorker, this.waOptions.vfs);
            const workerDBOpener = Comlink.wrap(workerPort);
            return new WorkerWrappedAsyncDatabaseConnection({
                remote: workerDBOpener,
                // This tab owns the worker, so we're guaranteed to outlive it.
                remoteCanCloseUnexpectedly: false,
                baseConnection: await workerDBOpener({
                    dbFilename: this.options.dbFilename,
                    vfs,
                    temporaryStorage,
                    cacheSizeKb,
                    flags: this.resolvedFlags,
                    encryptionKey: encryptionKey,
                    logLevel: this.logger.getLevel()
                }),
                identifier: this.options.dbFilename,
                onClose: () => {
                    if (workerPort instanceof Worker) {
                        workerPort.terminate();
                    }
                    else {
                        workerPort.close();
                    }
                }
            });
        }
        else {
            // Don't use a web worker
            return new WASqliteConnection({
                dbFilename: this.options.dbFilename,
                dbLocation: this.options.dbLocation,
                debugMode: this.options.debugMode,
                vfs,
                temporaryStorage,
                cacheSizeKb,
                flags: this.resolvedFlags,
                encryptionKey: encryptionKey
            });
        }
    }
}
/**
 * Asserts that the factory options are valid.
 */
function assertValidWASQLiteOpenFactoryOptions(options) {
    // The OPFS VFS only works in dedicated web workers.
    if ('vfs' in options && 'flags' in options) {
        const { vfs, flags = {} } = options;
        if (vfs !== WASQLiteVFS.IDBBatchAtomicVFS && 'useWebWorker' in flags && !flags.useWebWorker) {
            throw new Error(`Invalid configuration: The 'useWebWorker' flag must be true when using an OPFS-based VFS (${vfs}).`);
        }
    }
}
