import { Observable, Subscription } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { Connection } from '@workbench-stack/extension-api';
import { Services } from '../services/services';
import { IExtensionHostClient, IExtensionHostClientConnection } from '@workbench-stack/extension-api';
import { createExtensionHostClientConnection } from './connection';
import { logger } from '@cdm-logger/client';
/**
 * Creates a client to communicate with an extension host.
 *
 * @param services
 * @param extensionHostConnection An observable that emits the connection the extension host each time a new
 * connection is established.
 */
export function createExtensionHostClient(
    services: Services,
    extensionHostConnection: Observable<Connection>,
): IExtensionHostClient {
    const subscriptions = new Subscription();
    logger.info('--createExtensionHostClient called');

    const client = extensionHostConnection.pipe(
        switchMap(connection => {
            const clientCon = createExtensionHostClientConnection(connection, services);
            return new Observable<IExtensionHostClientConnection>(sub => {
                sub.next(clientCon);
                return () => clientCon.unsubscribe();
            });
        }),
    );
    subscriptions.add(client.subscribe());

    return {
        unsubscribe: () => subscriptions.unsubscribe(),
    };
}
