import * as _ from 'lodash';
import React from 'react';
import { ExtensionContext } from '@workbench-stack/components';
import { ContributableViewContainer } from '@workbench-stack/extension-api';
import { Subscription } from 'rxjs';
import { map } from 'rxjs/operators';
import { PanelView } from './Panelview';

function byPriority(a: { priority: number }, b: { priority: number }): number {
    return b.priority - a.priority;
}

export class ViewSlot extends React.Component<any, any> {
    public state: any = {};

    private subscriptions = new Subscription();

    public componentDidMount(): void {
        this.subscriptions.add(
            this.props.controller.services.views
                .getViews(ContributableViewContainer.Panel)
                .pipe(map(panelViews => ({ panelViews })))
                .subscribe(stateUpdate => this.setState(stateUpdate)),
        );
    }

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

    public get items() {
        return this.state.panelViews
        ? this.state.panelViews
              .map(
                  (panelView): any => ({
                      id: panelView.id,
                      label: panelView.title,
                      content: panelView.content,
                      priority: panelView.priority,
                      hasLocations: !!panelView.locationProvider,
                      element: <PanelView {...this.props as any} panelView={panelView} />,
                  }),
              )
              .sort(byPriority)
        : [];
    }

    public render() {
        return (
            <>
                {this.items.map(({ content, id, label, element }) => element)}
            </>
        );
    }
}
