import { from, Subscription } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { Connection, ClientThreadClientConfigurationShape, WebExtHostClientConfigurationShape,
    createProxyAndHandleRequests, ISettingsService,
} from '@workbench-stack/extension-api';
import { ISettingsEdit } from '@workbench-stack/core';

/**
 * @internal
 * @template C - The configuration schema.
 */
export class ClientConfiguration<C> implements ClientThreadClientConfigurationShape {
    private subscriptions = new Subscription();
    private proxy: WebExtHostClientConfigurationShape<C>;

    constructor(connection: Connection, private settingsService: ISettingsService) {
        this.proxy = createProxyAndHandleRequests('configuration', connection, this);
        this.subscriptions.add(
            from(settingsService.data)
                .pipe(
                    switchMap((settings: any) => {
                        // Only send valid settings.
                        //
                        // TODO(sqs): This could cause problems where the settings seen by extensions will lag behind
                        // settings seen by the client.
                        // if (isSettingsValue(settings)) {

                            // TODO: Implement handler
                            return this.proxy.$acceptConfigurationData(settings );
                        // }
                        return [];
                    }),
                )
                .subscribe(),
        );
    }

    public async $acceptConfigurationUpdate(edit: ISettingsEdit) {
        await this.settingsService.update(edit);
    }

    public unsubscribe(): void {
        this.subscriptions.unsubscribe();
    }
}
