import { computed } from "mobx";
import { observer } from "mobx-react";
import * as React from "react";
import { Doc, DocListCast } from "../../fields/Doc";
import { Id } from "../../fields/FieldSymbols";
import { Cast, NumCast, StrCast } from "../../fields/Types";
import { CollectionDockingView } from "./collections/CollectionDockingView";
import { CollectionViewType } from "./collections/CollectionView";
import './PropertiesDocContextSelector.scss';

type PropertiesDocContextSelectorProps = {
    Document: Doc,
    Stack?: any,
    hideTitle?: boolean,
    addDocTab(doc: Doc, location: string): void
};

@observer
export class PropertiesDocContextSelector extends React.Component<PropertiesDocContextSelectorProps> {
    @computed get _docs() {
        const target = this.props.Document;
        const aliases = DocListCast(target.aliases);
        const containerProtos = aliases.filter(alias => alias.context).reduce((set, alias) => set.add(Cast(alias.context, Doc, null)), new Set<Doc>());
        const containerSets = Array.from(containerProtos.keys()).map(container => DocListCast(container.aliases));
        const containers = containerSets.reduce((p, set) => { set.map(s => p.add(s)); return p; }, new Set<Doc>());
        const doclayoutSets = Array.from(containers.keys()).map(dp => DocListCast(dp.aliases));
        const doclayouts = Array.from(doclayoutSets.reduce((p, set) => { set.map(s => p.add(s)); return p; }, new Set<Doc>()).keys());
        return doclayouts.filter(doc => !Doc.AreProtosEqual(doc, CollectionDockingView.Instance.props.Document)).filter(doc => !Doc.IsSystem(doc)).map(doc => ({ col: doc, target }));
    }

    getOnClick = (col: Doc, target: Doc) => {
        col = Doc.IsPrototype(col) ? Doc.MakeDelegate(col) : col;
        if (col._viewType === CollectionViewType.Freeform) {
            col._panX = NumCast(target.x) + NumCast(target._width) / 2;
            col._panY = NumCast(target.y) + NumCast(target._height) / 2;
        }
        this.props.addDocTab(col, "add:right");
    }

    render() {
        return <div>
            {this.props.hideTitle ? (null) : <p key="contexts">Contexts:</p>}
            {this._docs.map(doc => <p key={doc.col[Id] + doc.target[Id]}><a onClick={() => this.getOnClick(doc.col, doc.target)}>{StrCast(doc.col.title)}</a></p>)}
        </div>;
    }
}