import { observer } from 'mobx-react';
import * as React from 'react';
import { DocumentView } from './DocumentView';
import { DocumentManager } from '../../util/DocumentManager';
import { Transformer, ts } from '../../util/Scripting';
import { Field } from '../../../fields/Doc';
import { Tooltip } from '@mui/material';
import { action, observable } from 'mobx';
import { Id } from '../../../fields/FieldSymbols';
import { factory } from 'typescript';
import { LightboxView } from '../LightboxView';
import { SettingsManager } from '../../util/SettingsManager';

@observer
export class DocumentIcon extends React.Component<{ view: DocumentView; index: number }> {
    @observable _hovered = false;
    static get DocViews() {
        return LightboxView.LightboxDoc ? DocumentManager.Instance.DocumentViews.filter(v => LightboxView.IsLightboxDocView(v.props.docViewPath())) : DocumentManager.Instance.DocumentViews;
    }
    render() {
        const view = this.props.view;
        const { left, top, right, bottom } = view.getBounds() || { left: 0, top: 0, right: 0, bottom: 0 };

        return (
            <div
                className="documentIcon-outerDiv"
                onPointerEnter={action(e => (this._hovered = true))}
                onPointerLeave={action(e => (this._hovered = false))}
                style={{
                    pointerEvents: 'all',
                    opacity: this._hovered ? 0.3 : 1,
                    position: 'absolute',
                    background: SettingsManager.userBackgroundColor,
                    transform: `translate(${(left + right) / 2}px, ${top}px)`,
                }}>
                <Tooltip title={<>{this.props.view.Document.title}</>}>
                    <p>d{this.props.index}</p>
                </Tooltip>
            </div>
        );
    }
}

@observer
export class DocumentIconContainer extends React.Component {
    public static getTransformer(): Transformer {
        const usedDocuments = new Set<number>();
        return {
            transformer: context => {
                return root => {
                    function visit(node: ts.Node) {
                        node = ts.visitEachChild(node, visit, context);

                        if (ts.isIdentifier(node)) {
                            const isntPropAccess = !ts.isPropertyAccessExpression(node.parent) || node.parent.expression === node;
                            const isntPropAssign = !ts.isPropertyAssignment(node.parent) || node.parent.name !== node;
                            const isntParameter = !ts.isParameter(node.parent);
                            if (isntPropAccess && isntPropAssign && isntParameter && !(node.text in globalThis)) {
                                const match = node.text.match(/d([0-9]+)/);
                                if (match) {
                                    const m = parseInt(match[1]);
                                    const doc = DocumentIcon.DocViews[m].Document;
                                    usedDocuments.add(m);
                                    return factory.createIdentifier(`idToDoc("${doc[Id]}")`);
                                }
                            }
                        }

                        return node;
                    }
                    return ts.visitNode(root, visit);
                };
            },
            getVars() {
                const docs = DocumentIcon.DocViews;
                const capturedVariables: { [name: string]: Field } = {};
                usedDocuments.forEach(index => (capturedVariables[`d${index}`] = docs.length > index ? docs[index].props.Document : `d${index}`));
                return capturedVariables;
            },
        };
    }
    render() {
        return DocumentIcon.DocViews.map((dv, i) => <DocumentIcon key={i} index={i} view={dv} />);
    }
}
