import { Unsubscribable } from 'rxjs';
import * as cdecode from 'cdecode/client';
import { ProviderMap, PanelViewData, ClientThreadViewsShape } from '@workbench-stack/extension-api';

/**
 * @internal
 */
class WebExtHostPanelView implements cdecode.PanelView {
    private data: PanelViewData = {
        title: '',
        content: '',
        priority: 0,
        component: null,
    };

    constructor(private proxy: ClientThreadViewsShape, private id: number, private subscription: Unsubscribable) { }

    public get title(): string {
        return this.data.title;
    }

    public set title(value: string) {
        this.data.title = value;
        this.sendData();
    }

    public get content(): string {
        return this.data.content;
    }

    public set content(value: string) {
        this.data.content = value;
        this.sendData();
    }

    public get priority(): number {
        return this.data.priority;
    }

    public set priority(value: number) {
        this.data.priority = value;
        this.sendData();
    }

    public get component(): cdecode.PanelView['component'] {
        return this.data.component;
    }

    public set component(value: cdecode.PanelView['component']) {
        this.data.component = value;
        this.sendData();
    }

    public sendData(): void {
        this.proxy.$acceptPanelViewUpdate(this.id, this.data);
    }

    public unsubscribe(): void {
        return this.subscription.unsubscribe();
    }
}


/** @internal */
export class WebExtHostViews implements Unsubscribable {
    private registrations = new ProviderMap<{}>(id => this.proxy.$unregister(id));

    constructor(private proxy: ClientThreadViewsShape) { }

    public createPanelView(id: string): WebExtHostPanelView {
        const { id: regID, subscription } = this.registrations.add({});
        this.proxy.$registerPanelViewProvider(regID, { id });
        return new WebExtHostPanelView(this.proxy, regID, subscription);
    }

    public createEditorPreview(editorId: string): WebExtHostPanelView {
        const { id: regID, subscription } = this.registrations.add({});
        this.proxy.$registerPanelViewProvider(regID, { id: `EditorPreview.${editorId}` });
        return new WebExtHostPanelView(this.proxy, regID, subscription);
    }

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