import * as Comlink from 'comlink';
import { resolveWebPowerSyncFlags } from '../../PowerSyncDatabase.js';
import { DEFAULT_CACHE_SIZE_KB, TemporaryStorageOption } from '../web-sql-flags.js';
import { WorkerWrappedAsyncDatabaseConnection } from '../WorkerWrappedAsyncDatabaseConnection.js';
import { InternalWASQLiteDBAdapter } from './InternalWASQLiteDBAdapter.js';
import { WASQLiteOpenFactory } from './WASQLiteOpenFactory.js';
/**
 * Adapter for WA-SQLite SQLite connections.
 */
export class WASQLiteDBAdapter extends InternalWASQLiteDBAdapter {
    constructor(options) {
        super({
            name: options.dbFilename,
            openConnection: async () => {
                const { workerPort, temporaryStorage, cacheSizeKb } = options;
                if (workerPort) {
                    const remote = Comlink.wrap(workerPort);
                    return new WorkerWrappedAsyncDatabaseConnection({
                        remote,
                        remoteCanCloseUnexpectedly: false,
                        identifier: options.dbFilename,
                        baseConnection: await remote({
                            ...options,
                            temporaryStorage: temporaryStorage ?? TemporaryStorageOption.MEMORY,
                            cacheSizeKb: cacheSizeKb ?? DEFAULT_CACHE_SIZE_KB,
                            flags: resolveWebPowerSyncFlags(options.flags),
                            encryptionKey: options.encryptionKey
                        })
                    });
                }
                const openFactory = new WASQLiteOpenFactory({
                    dbFilename: options.dbFilename,
                    dbLocation: options.dbLocation,
                    debugMode: options.debugMode,
                    flags: options.flags,
                    temporaryStorage,
                    cacheSizeKb,
                    logger: options.logger,
                    vfs: options.vfs,
                    encryptionKey: options.encryptionKey,
                    worker: options.worker
                });
                return openFactory.openConnection();
            },
            debugMode: options.debugMode,
            logger: options.logger
        });
    }
}
