import { observer } from 'mobx-react';
import * as React from 'react';
import { Doc } from '../../fields/Doc';
import { Cast } from '../../fields/Types';
import { DocumentType } from '../documents/DocumentTypes';
import { LinkManager } from '../util/LinkManager';
import { SelectionManager } from '../util/SelectionManager';
import { LinkMenu } from './linking/LinkMenu';
import { OpenWhere, OpenWhereMod } from './nodes/DocumentView';
import './PropertiesDocBacklinksSelector.scss';

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

@observer
export class PropertiesDocBacklinksSelector extends React.Component<PropertiesDocBacklinksSelectorProps> {
    getOnClick = (link: Doc) => {
        const linkAnchor = this.props.Document;
        const other = LinkManager.getOppositeAnchor(link, linkAnchor);
        const otherdoc = !other ? undefined : other.annotationOn && other.type !== DocumentType.RTF ? Cast(other.annotationOn, Doc, null) : other;

        if (otherdoc) {
            otherdoc.hidden = false;
            this.props.addDocTab(Doc.IsDataProto(otherdoc) ? Doc.MakeDelegate(otherdoc) : otherdoc, OpenWhere.toggleRight);
        }
    };

    render() {
        return !SelectionManager.Views().length ? null : (
            <div className="preroptiesDocBacklinksSelector">
                {this.props.hideTitle ? null : <p key="contexts">Contexts:</p>}
                <LinkMenu docView={SelectionManager.Views().lastElement()} clearLinkEditor={undefined} itemHandler={this.getOnClick} style={{ left: 0, top: 0 }} />
            </div>
        );
    }
}
