import { action, computed, observable } from 'mobx';
import { observer } from 'mobx-react';
import { Doc } from '../../../fields/Doc';
import { LinkManager } from '../../util/LinkManager';
import { DocumentView } from '../nodes/DocumentView';
import { LinkDocPreview } from '../nodes/LinkDocPreview';
import { LinkEditor } from './LinkEditor';
import './LinkMenu.scss';
import { LinkMenuGroup } from './LinkMenuGroup';
import React = require('react');

interface Props {
    docView: DocumentView;
    position?: { x?: number; y?: number };
    itemHandler?: (doc: Doc) => void;
    clearLinkEditor: () => void;
}

/**
 * the outermost component for the link menu of a node that contains a list of its linked nodes
 */
@observer
export class LinkMenu extends React.Component<Props> {
    _editorRef = React.createRef<HTMLDivElement>();
    @observable _editingLink?: Doc;
    @observable _linkMenuRef = React.createRef<HTMLDivElement>();

    @computed get position() {
        return this.props.position ?? (dv => ({ x: dv?.left || 0, y: (dv?.bottom || 0) + 15 }))(this.props.docView.getBounds());
    }

    clear = action(() => {
        this.props.clearLinkEditor();
        this._editingLink = undefined;
    });

    componentDidMount() {
        document.addEventListener('pointerdown', this.onPointerDown, true);
    }
    componentWillUnmount() {
        document.removeEventListener('pointerdown', this.onPointerDown, true);
    }

    onPointerDown = action((e: PointerEvent) => {
        LinkDocPreview.Clear();
        if (!this._linkMenuRef.current?.contains(e.target as any) && !this._editorRef.current?.contains(e.target as any)) {
            this.clear();
        }
    });

    /**
     * maps each link to a JSX element to be rendered
     * @param groups containing info of all of the links
     * @returns list of link JSX elements if there at least one linked element
     */
    renderAllGroups = (groups: Map<string, Array<Doc>>): Array<JSX.Element> => {
        const linkItems = Array.from(groups.entries()).map(group => (
            <LinkMenuGroup
                key={group[0]}
                itemHandler={this.props.itemHandler}
                docView={this.props.docView}
                sourceDoc={this.props.docView.props.Document}
                group={group[1]}
                groupType={group[0]}
                clearLinkEditor={this.clear}
                showEditor={action(linkDoc => (this._editingLink = linkDoc))}
            />
        ));

        return linkItems.length ? linkItems : this.props.position ? [<></>] : [<p key="">No links have been created yet. Drag the linking button onto another document to create a link.</p>];
    };

    render() {
        const sourceDoc = this.props.docView.props.Document;
        return (
            <div className="linkMenu" ref={this._linkMenuRef} style={{ left: this.position.x, top: this.props.docView.topMost ? undefined : this.position.y, bottom: this.props.docView.topMost ? 20 : undefined }}>
                {this._editingLink ? (
                    <div className="linkMenu-listEditor">
                        <LinkEditor sourceDoc={sourceDoc} linkDoc={this._editingLink} showLinks={action(() => (this._editingLink = undefined))} />
                    </div>
                ) : (
                    <div className="linkMenu-list">{this.renderAllGroups(LinkManager.Instance.getRelatedGroupedLinks(sourceDoc))}</div>
                )}
            </div>
        );
    }
}
