import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { action, computed, IReactionDisposer, observable, reaction } from "mobx";
import { observer } from "mobx-react";
import { DataSym, Doc, DocListCast, HeightSym, Opt, StrListCast, WidthSym } from '../../../fields/Doc';
import { Id } from '../../../fields/FieldSymbols';
import { InkTool } from '../../../fields/InkField';
import { Document, listSpec } from '../../../fields/Schema';
import { ScriptField } from '../../../fields/ScriptField';
import { BoolCast, Cast, NumCast, ScriptCast, StrCast } from '../../../fields/Types';
import { TraceMobx } from '../../../fields/util';
import { returnEmptyDoclist, returnEmptyFilter, returnFalse, returnTrue, emptyFunction } from '../../../Utils';
import { DocUtils } from '../../documents/Documents';
import { CurrentUserUtils } from '../../util/CurrentUserUtils';
import { DocumentManager } from '../../util/DocumentManager';
import { DragManager, dropActionType } from "../../util/DragManager";
import { SelectionManager } from '../../util/SelectionManager';
import { SnappingManager } from '../../util/SnappingManager';
import { undoBatch, UndoManager } from '../../util/UndoManager';
import { ContextMenu } from '../ContextMenu';
import { ContextMenuProps } from '../ContextMenuItem';
import { EditableView } from "../EditableView";
import { DocumentView } from '../nodes/DocumentView';
import { FormattedTextBox } from '../nodes/formattedText/FormattedTextBox';
import { StyleProp } from '../StyleProvider';
import { CollectionSubView } from "./CollectionSubView";
import "./CollectionTreeView.scss";
import { TreeView } from "./TreeView";
import React = require("react");
import { Transform } from '../../util/Transform';
const _global = (window /* browser */ || global /* node */) as any;

export type collectionTreeViewProps = {
    treeViewExpandedView?: "fields" | "layout" | "links" | "data";
    treeViewOpen?: boolean;
    treeViewHideTitle?: boolean;
    treeViewHideHeaderFields?: boolean;
    treeViewSkipFields?: string[]; // prevents specific fields from being displayed (see LinkBox)
    onCheckedClick?: () => ScriptField;
    onChildClick?: () => ScriptField;
};

@observer
export class CollectionTreeView extends CollectionSubView<Document, Partial<collectionTreeViewProps>>(Document) {
    private treedropDisposer?: DragManager.DragDropDisposer;
    private _mainEle?: HTMLDivElement;
    private _disposers: { [name: string]: IReactionDisposer } = {};
    MainEle = () => this._mainEle;

    @computed get doc() { return this.props.Document; }
    @computed get dataDoc() { return this.props.DataDoc || this.doc; }
    @computed get treeViewtruncateTitleWidth() { return NumCast(this.doc.treeViewTruncateTitleWidth, this.panelWidth()); }
    @computed get treeChildren() { TraceMobx(); return this.props.childDocuments || this.childDocs; }
    @computed get outlineMode() { return this.doc.treeViewType === "outline"; }
    @computed get fileSysMode() { return this.doc.treeViewType === "fileSystem"; }
    @computed get dashboardMode() { return this.doc === Doc.UserDoc().myDashboards; }

    // these should stay in synch with counterparts in DocComponent.ts ViewBoxAnnotatableComponent
    @observable _isAnyChildContentActive = false;
    whenChildContentsActiveChanged = action((isActive: boolean) => this.props.whenChildContentsActiveChanged(this._isAnyChildContentActive = isActive));
    isContentActive = (outsideReaction?: boolean) => (CurrentUserUtils.SelectedTool !== InkTool.None ||
        (this.props.isContentActive?.() || this.props.Document.forceActive ||
            this.props.isSelected(outsideReaction) || this._isAnyChildContentActive ||
            this.props.rootSelected(outsideReaction)) ? true : false)

    isDisposing = false;
    componentWillUnmount() {
        this.isDisposing = true;
        super.componentWillUnmount();
        this.treedropDisposer?.();
        Object.values(this._disposers).forEach(disposer => disposer?.());
    }

    componentDidMount() {
        this._disposers.autoheight = reaction(() => this.rootDoc.autoHeight,
            auto => auto && this.computeHeight(),
            { fireImmediately: true });
    }

    refList: Set<any> = new Set();
    observer: any;
    computeHeight = () => {
        if (this.isDisposing) return;
        const bodyHeight = Array.from(this.refList).reduce((p, r) => p + Number(getComputedStyle(r).height.replace("px", "")), this.paddingTop() + this.paddingBot());
        this.layoutDoc._autoHeightMargins = bodyHeight;
        this.props.setHeight(this.documentTitleHeight() + bodyHeight);
    }
    unobserveHeight = (ref: any) => {
        this.refList.delete(ref);
        this.rootDoc.autoHeight && this.computeHeight();
    }
    observeHeight = (ref: any) => {
        if (ref) {
            this.refList.add(ref);
            this.observer = new _global.ResizeObserver(action((entries: any) => {
                if (this.rootDoc.autoHeight && ref && this.refList.size && !SnappingManager.GetIsDragging()) {
                    this.computeHeight();
                }
            }));
            this.rootDoc.autoHeight && this.computeHeight();
            this.observer.observe(ref);
        }
    }
    protected createTreeDropTarget = (ele: HTMLDivElement) => {
        this.treedropDisposer?.();
        if (this._mainEle = ele) this.treedropDisposer = DragManager.MakeDropTarget(ele, this.onInternalDrop.bind(this), this.doc, this.onInternalPreDrop.bind(this));
    }

    protected onInternalPreDrop = (e: Event, de: DragManager.DropEvent, targetAction: dropActionType) => {
        const dragData = de.complete.docDragData;
        if (dragData) {
            const isInTree = () => dragData.draggedDocuments.some(d => d.context === this.doc && this.childDocs.includes(d));
            dragData.dropAction = targetAction && !isInTree() ? targetAction : this.doc === dragData?.treeViewDoc ? "same" : dragData.dropAction;
        }
    }

    @action
    remove = (doc: Doc | Doc[]): boolean => {
        const docs = doc instanceof Doc ? [doc] : doc;
        const targetDataDoc = this.doc[DataSym];
        const value = DocListCast(targetDataDoc[this.props.fieldKey]);
        const result = value.filter(v => !docs.includes(v));
        if ((doc instanceof Doc ? [doc] : doc).some(doc => SelectionManager.Views().some(dv => Doc.AreProtosEqual(dv.rootDoc, doc)))) SelectionManager.DeselectAll();
        if (result.length !== value.length) {
            const ind = targetDataDoc[this.props.fieldKey].indexOf(doc);
            const prev = ind && targetDataDoc[this.props.fieldKey][ind - 1];
            this.props.removeDocument?.(doc);
            if (ind > 0) {
                FormattedTextBox.SelectOnLoad = prev[Id];
                DocumentManager.Instance.getDocumentView(prev, this.props.CollectionView)?.select(false);
            }
            return true;
        }
        return false;
    }

    @action
    addDoc = (docs: Doc | Doc[], relativeTo: Opt<Doc>, before?: boolean): boolean => {
        const doAddDoc = (doc: Doc | Doc[]) =>
            (doc instanceof Doc ? [doc] : doc).reduce((flg, doc) => {
                const res = flg && Doc.AddDocToList(this.doc[DataSym], this.props.fieldKey, doc, relativeTo, before);
                res && (doc.context = this.props.Document);
                return res;
            }, true);
        if (this.doc.resolvedDataDoc instanceof Promise) return false;
        return relativeTo === undefined ? this.props.addDocument?.(docs) || false : doAddDoc(docs);
    }
    onContextMenu = (e: React.MouseEvent): void => {
        // need to test if propagation has stopped because GoldenLayout forces a parallel react hierarchy to be created for its top-level layout
        if (!Doc.UserDoc().noviceMode) {
            const layoutItems: ContextMenuProps[] = [];
            layoutItems.push({ description: "Make tree state " + (this.doc.treeViewOpenIsTransient ? "persistent" : "transient"), event: () => this.doc.treeViewOpenIsTransient = !this.doc.treeViewOpenIsTransient, icon: "paint-brush" });
            layoutItems.push({ description: (this.doc.treeViewHideHeaderFields ? "Show" : "Hide") + " Header Fields", event: () => this.doc.treeViewHideHeaderFields = !this.doc.treeViewHideHeaderFields, icon: "paint-brush" });
            layoutItems.push({ description: (this.doc.treeViewHideTitle ? "Show" : "Hide") + " Title", event: () => this.doc.treeViewHideTitle = !this.doc.treeViewHideTitle, icon: "paint-brush" });
            ContextMenu.Instance.addItem({ description: "Options...", subitems: layoutItems, icon: "eye" });
            const existingOnClick = ContextMenu.Instance.findByDescription("OnClick...");
            const onClicks: ContextMenuProps[] = existingOnClick && "subitems" in existingOnClick ? existingOnClick.subitems : [];
            onClicks.push({ description: "Edit onChecked Script", event: () => UndoManager.RunInBatch(() => DocUtils.makeCustomViewClicked(this.doc, undefined, "onCheckedClick"), "edit onCheckedClick"), icon: "edit" });
            !existingOnClick && ContextMenu.Instance.addItem({ description: "OnClick...", noexpand: true, subitems: onClicks, icon: "mouse-pointer" });
        }
    }
    onTreeDrop = (e: React.DragEvent, addDocs?: (docs: Doc[]) => void) => this.onExternalDrop(e, {}, addDocs);

    @undoBatch
    makeTextCollection = (childDocs: Doc[]) => {
        this.addDoc(TreeView.makeTextBullet(), childDocs.length ? childDocs[0] : undefined, true);
    }

    editableTitle = (childDocs: Doc[]) => {
        return !this.dataDoc ? (null) :
            <EditableView
                contents={this.dataDoc.title}
                display={"block"}
                maxHeight={72}
                height={"auto"}
                GetValue={() => StrCast(this.dataDoc.title)}
                SetValue={undoBatch((value: string, shift: boolean, enter: boolean) => {
                    if (enter && this.props.Document.treeViewType === "outline") this.makeTextCollection(childDocs);
                    this.dataDoc.title = value;
                    return true;
                })} />;
    }


    documentTitle = (childDocs: Doc[]) => {
        return <div style={{ display: "inline-block", width: "100%", height: this.documentTitleHeight() }} key={this.doc[Id]}
            onKeyDown={e => {
                e.stopPropagation();
                e.key === "Enter" && this.makeTextCollection(childDocs);
            }}>
            <DocumentView
                Document={this.doc}
                DataDoc={undefined}
                LayoutTemplateString={FormattedTextBox.LayoutString("text")}
                renderDepth={this.props.renderDepth + 1}
                isContentActive={this.isContentActive}
                isDocumentActive={this.isContentActive}
                rootSelected={returnTrue}
                docViewPath={this.props.docViewPath}
                styleProvider={this.props.styleProvider}
                layerProvider={this.props.layerProvider}
                PanelWidth={this.documentTitleWidth}
                PanelHeight={this.documentTitleHeight}
                NativeWidth={this.documentTitleWidth}
                NativeHeight={this.documentTitleHeight}
                focus={this.props.focus}
                treeViewDoc={this.props.Document}
                ScreenToLocalTransform={this.titleTransform}
                docFilters={returnEmptyFilter}
                docRangeFilters={returnEmptyFilter}
                searchFilterDocs={returnEmptyDoclist}
                ContainingCollectionDoc={this.doc}
                ContainingCollectionView={this.props.CollectionView}
                addDocument={this.props.addDocument}
                moveDocument={returnFalse}
                removeDocument={returnFalse}
                whenChildContentsActiveChanged={this.whenChildContentsActiveChanged}
                addDocTab={this.props.addDocTab}
                pinToPres={this.props.pinToPres}
                bringToFront={returnFalse}
            />
        </div>;
    }
    childContextMenuItems = () => {
        const customScripts = Cast(this.doc.childContextMenuScripts, listSpec(ScriptField), []);
        const customFilters = Cast(this.doc.childContextMenuFilters, listSpec(ScriptField), []);
        const icons = StrListCast(this.doc.childContextMenuIcons);
        return StrListCast(this.doc.childContextMenuLabels).map((label, i) => ({ script: customScripts[i], filter: customFilters[i], icon: icons[i], label }));
    }
    @computed get treeViewElements() {
        TraceMobx();
        const dropAction = StrCast(this.doc.childDropAction) as dropActionType;
        const addDoc = (doc: Doc | Doc[], relativeTo?: Doc, before?: boolean) => this.addDoc(doc, relativeTo, before);
        const moveDoc = (d: Doc | Doc[], target: Doc | undefined, addDoc: (doc: Doc | Doc[]) => boolean) => this.props.moveDocument?.(d, target, addDoc) || false;
        return TreeView.GetChildElements(
            this.treeChildren,
            this,
            this,
            this.doc,
            this.props.DataDoc,
            this.props.ContainingCollectionDoc,
            undefined,
            addDoc,
            this.remove,
            moveDoc,
            dropAction,
            this.props.addDocTab,
            this.props.styleProvider,
            this.props.ScreenToLocalTransform,
            this.isContentActive,
            this.panelWidth,
            this.props.renderDepth,
            () => this.props.treeViewHideHeaderFields || BoolCast(this.doc.treeViewHideHeaderFields),
            [],
            this.props.onCheckedClick,
            this.onChildClick,
            this.props.treeViewSkipFields,
            true,
            this.whenChildContentsActiveChanged,
            this.props.dontRegisterView || Cast(this.props.Document.childDontRegisterViews, "boolean", null),
            this.observeHeight,
            this.unobserveHeight,
            this.childContextMenuItems()
        );
    }
    @computed get titleBar() {
        const hideTitle = this.props.treeViewHideTitle || this.doc.treeViewHideTitle;
        return hideTitle ? (null) : (this.outlineMode ? this.documentTitle : this.editableTitle)(this.treeChildren);
    }

    @computed get buttonMenu() {
        const menuDoc:Doc = Cast(this.rootDoc.buttonMenuDoc, Doc, null);
        // To create a multibutton menu add a CollectionLinearView
        if (menuDoc){
            
            const width: number = NumCast(menuDoc._width, 30);
            const height: number = NumCast(menuDoc._height, 30);
            console.log(menuDoc.title, width, height);
            return (<div className="buttonMenu-docBtn"
                style = {{width: width, height: height}}>
                <DocumentView
                    Document={menuDoc}
                    DataDoc={menuDoc}
                    isContentActive={this.props.isContentActive}
                    isDocumentActive={returnTrue}
                    addDocument={this.props.addDocument}
                    moveDocument={this.props.moveDocument}
                    addDocTab={this.props.addDocTab}
                    pinToPres={emptyFunction}
                    rootSelected={this.props.isSelected}
                    removeDocument={this.props.removeDocument}
                    ScreenToLocalTransform={Transform.Identity}
                    PanelWidth={() => 35}
                    PanelHeight={() => 35}
                    renderDepth={this.props.renderDepth + 1}
                    focus={emptyFunction}
                    styleProvider={this.props.styleProvider}
                    layerProvider={this.props.layerProvider}
                    docViewPath={returnEmptyDoclist}
                    whenChildContentsActiveChanged={emptyFunction}
                    bringToFront={emptyFunction}
                    docFilters={this.props.docFilters}
                    docRangeFilters={this.props.docRangeFilters}
                    searchFilterDocs={this.props.searchFilterDocs}
                    ContainingCollectionView={undefined}
                    ContainingCollectionDoc={undefined} 
                />
            </div>);
        }
    }

    
    @computed get nativeWidth() { return Doc.NativeWidth(this.Document, undefined, true); }
    @computed get nativeHeight() { return Doc.NativeHeight(this.Document, undefined, true); }

    @computed get contentScaling() {
        const nw = this.nativeWidth;
        const nh = this.nativeHeight;
        const hscale = nh ? this.props.PanelHeight() / nh : 1;
        const wscale = nw ? this.props.PanelWidth() / nw : 1;
        return wscale < hscale ? wscale : hscale;
    }
    paddingX = () => NumCast(this.doc._xPadding, 15);
    paddingTop = () => NumCast(this.doc._yPadding, 20);
    paddingBot = () => NumCast(this.doc._yPadding, 20);
    documentTitleWidth = () => Math.min(this.layoutDoc?.[WidthSym](), this.panelWidth());
    documentTitleHeight = () => (this.layoutDoc?.[HeightSym]() || 0) - NumCast(this.layoutDoc.autoHeightMargins);
    titleTransform = () => this.props.ScreenToLocalTransform().translate(-NumCast(this.doc._xPadding, 10), -NumCast(this.doc._yPadding, 20));
    truncateTitleWidth = () => this.treeViewtruncateTitleWidth;
    onChildClick = () => this.props.onChildClick?.() || ScriptCast(this.doc.onChildClick);
    panelWidth = () => (this.props.PanelWidth() - 2 * this.paddingX()) * (this.props.scaling?.() || 1);
    render() {
        TraceMobx();
        const background = () => this.props.styleProvider?.(this.doc, this.props, StyleProp.BackgroundColor);
        const pointerEvents = () => !this.props.isContentActive() && !SnappingManager.GetIsDragging() ? "none" : undefined;
        const buttonMenu = this.rootDoc.buttonMenu;
        const noviceExplainer = this.rootDoc.explainer;

        return !(this.doc instanceof Doc) || !this.treeChildren ? (null) :
               <>
                    {this.titleBar}
                    <div className="collectionTreeView-container"
                        style={this.outlineMode ? { transform: `scale(${this.contentScaling})`, width: `calc(${100 / this.contentScaling}%)` } : {}}
                        onContextMenu={this.onContextMenu}>
                        {buttonMenu || noviceExplainer ? <div className="documentButtonMenu">
                            {buttonMenu ? this.buttonMenu : null}
                            {Doc.UserDoc().noviceMode && noviceExplainer ? 
                                <div className="documentExplanation">
                                    {noviceExplainer}
                                </div>
                                : null
                            }
                        </div> : null}
                        <div className="collectionTreeView-dropTarget"
                            style={{ background: background(), paddingLeft: `${this.paddingX()}px`, paddingRight: `${this.paddingX()}px`, paddingBottom: `${this.paddingBot()}px`, paddingTop: `${this.paddingTop()}px`, pointerEvents: pointerEvents() }}
                            onWheel={e => e.stopPropagation()}
                            onDrop={this.onTreeDrop}
                            ref={this.createTreeDropTarget}>
                            <ul className={`no-indent${this.outlineMode ? "-outline" : ""}`} >
                                {this.treeViewElements}
                            </ul>
                        </div >
                    </div>
               </>;
    }
}