import { action, computed, makeObservable, observable } from 'mobx';
import * as React from 'react';
import { returnFalse } from '../../ClientUtils';
import { DateField } from '../../fields/DateField';
import { Doc, DocListCast, Opt } from '../../fields/Doc';
import { AclAdmin, AclAugment, AclEdit, AclPrivate, AclReadonly, DocData, DocLayout } from '../../fields/DocSymbols';
import { List } from '../../fields/List';
import { DocCast, toList } from '../../fields/Types';
import { GetEffectiveAcl, inheritParentAcls } from '../../fields/util';
import { DocumentType } from '../documents/DocumentTypes';
import { ObservableReactComponent } from './ObservableReactComponent';
import { ViewBoxInterface } from './ViewBoxInterface';
import { FieldViewProps } from './nodes/FieldView';

/**
 * DocComponent returns a React base class used by Doc views with accessors for unpacking the Document,layoutDoc, and dataDoc's
 *  (note: this should not be used for the 'Box' views that render the contents of Doc views)
 *  Example derived views: CollectionFreeFormDocumentView, DocumentView, DocumentViewInternal)
 * */
export interface DocComponentProps {
    Document: Doc;
    TemplateDataDocument?: Doc;
    LayoutTemplate?: () => Opt<Doc>;
    LayoutTemplateString?: string;
}
export function DocComponent<P extends DocComponentProps>() {
    class Component extends ObservableReactComponent<React.PropsWithChildren<P>> {
        constructor(props: P) {
            super(props);
            makeObservable(this);
        }

        /**
         * This is the doc that is being rendered. It will be either:
         *   1) the same as Document if the root of a regular or compound Doc is rendered
         *   2) the same as the layoutDoc if a component of a compound Doc is rendered.
         * NOTE: it is very unlikely that you really want to use this method. Instead
         *       consider: Document, layoutDoc, dataDoc
         */
        get Document() {
            return this._props.Document;
        }

        /**
         * This is the "root" Doc being rendered.  In the case of a compound template Doc,
         * this is the outermost Doc that represents the entire compound Doc.  It is not
         * necessarily the Doc being rendered in the current React component.
         * This Doc inherits from the dataDoc, and may or may not inherit (or be) the layoutDoc.
         */
        get rootDoc() {
            return DocCast(this.Document.rootDocument, this.Document);
        }

        /**
         * Whether the doc is a sub-componentn of a compound template doc.
         */
        get isTemplateForField() {
            return this.rootDoc !== this.layoutDoc && this._props.TemplateDataDocument;
        }
        /**
         * This is the document being rendered by the React component. In the
         * case of a compound template, this will be the  expanded template Doc
         * that represents the component of the compound Doc being rendered.
         * This may or may not inherit from the data doc.
         */
        @computed get layoutDoc() {
            return this._props.LayoutTemplateString ? this.Document : Doc.Layout(this.Document, this._props.LayoutTemplate?.());
        }

        /**
         * This is the unique data repository for a document that stores the intrinsic document data.
         */
        @computed get dataDoc() {
            return this.Document[DocData];
        }
    }
    return Component;
}

/**
 *   base class for non-annotatable views that render the interior contents of a DocumentView.
 *   this unpacks the Document/layout/data docs as well as the fieldKey being rendered,
 *   and provides accessors for DocumentView and ScreenToLocalBoxXf
 *   Example views include: InkingStroke, FontIconBox, EquationBox, etc
 */
export function ViewBoxBaseComponent<P extends FieldViewProps>() {
    class Component extends ViewBoxInterface<P> {
        constructor(props: P) {
            super(props);
            makeObservable(this);
        }

        ScreenToLocalBoxXf = () => this._props.ScreenToLocalTransform();

        get DocumentView() {
            return this._props.DocumentView;
        }

        /**
         * This is the doc that is being rendered. It will be either:
         *   1) the same as Document if the root of a regular or compound Doc is rendered
         *   2) the same as the layoutDoc if a component of a compound Doc is rendered.
         */
        get Document() {
            return this._props.Document;
        }

        /**
         * This is the "root" Doc being rendered.  In the case of a compound template Doc,
         * this is the outermost Doc that represents the entire compound Doc.  It is not
         * necessarily the Doc being rendered in the current React component.
         * This Doc inherits from the dataDoc, and may or may not inherit (or be) the layoutDoc.
         *
         * NOTE: it is very unlikely that you really want to use this method. Instead
         *       consider: Document, layoutDoc, dataDoc
         */
        get rootDoc() {
            return DocCast(this.Document.rootDocument, this.Document);
        }
        /**
         * This is the document being rendered by the React component. In the
         * case of a compound template, this will be the  expanded template Doc
         * that represents the component of the compound Doc being rendered.
         * This may or may not inherit from the data doc.
         */
        @computed get layoutDoc() {
            return this.Document[DocLayout];
        }

        /**
         * This is the unique data repository for a dcoument that stores the intrinsic document data
         */
        @computed get dataDoc() {
            return this.Document.isTemplateForField || this.Document.isTemplateDoc ? (this._props.TemplateDataDocument ?? this.Document[DocData]) : this.Document[DocData];
        }

        /**
         * this is the field key where the primary rendering data is stored for the layout doc (e.g., it's often the 'data' field for a collection, or the 'text' field for rich text)
         */
        get fieldKey() {
            return this._props.fieldKey;
        }
    }
    return Component;
}

/**
 * base class for annotatable views that render the interior contents of a DocumentView
 * This does what ViewBoxBaseComponent does and additionally provides accessor for the
 * field key where annotations are stored as well as add/move/remove methods for handing
 * annotations.
 * This also provides methods to determine when the contents should be interactive
 * (respond to pointerEvents) such as when the DocumentView container is selected or a
 * peer child of the container is selected
 * Example views include: PDFBox, ImageBox, MapBox, etc
 */
export function ViewBoxAnnotatableComponent<P extends FieldViewProps>() {
    class Component extends ViewBoxInterface<P> {
        @observable _annotationKeySuffix = () => 'annotations';
        @observable _isAnyChildContentActive = false;

        constructor(props: P) {
            super(props);
            makeObservable(this);
        }

        ScreenToLocalBoxXf = () => this._props.ScreenToLocalTransform();

        get DocumentView() {
            return this._props.DocumentView;
        }

        /**
         * This is the doc that is being rendered. It will be either:
         *   1) the same as Document if the root of a regular or compound Doc is rendered
         *   2) the same as the layoutDoc if a component of a compound Doc is rendered.
         */
        get Document() {
            return this._props.Document;
        }

        /**
         * This is the "root" Doc being rendered.  In the case of a compound template Doc,
         * this is the outermost Doc that represents the entire compound Doc.  It is not
         * necessarily the Doc being rendered in the current React component.
         * This Doc inherits from the dataDoc, and may or may not inherit (or be) the layoutDoc.
         *
         * NOTE: it would unlikely that you really want to use this instead of the
         *       other Doc options (Document, layoutDoc, dataDoc)
         */
        @computed get rootDoc() {
            return DocCast(this.Document.rootDocument, this.Document);
        }
        /**
         * This is the document being rendered.  It may be a template so it may or may no inherit from the data doc.
         */
        @computed get layoutDoc() {
            return this.Document[DocLayout];
        }

        /**
         * This is the unique data repository for a dcoument that stores the intrinsic document data
         */
        @computed get dataDoc() {
            return this.Document.isTemplateForField || this.Document.isTemplateDoc ? 
                (this._props.TemplateDataDocument ?? this.Document[DocData]) : 
                this.Document[DocData]; // prettier-ignore
        }

        /**
         * this is the field key where the primary rendering data is stored for the layout doc (e.g., it's often the 'data' field for a collection, or the 'text' field for rich text)
         */
        @computed get fieldKey() {
            return this._props.fieldKey;
        }

        /**
         * this is field key where the list of annotations is stored
         */
        @computed public get annotationKey() {
            return this.fieldKey + (this._annotationKeySuffix() ? '_' + this._annotationKeySuffix() : '');
        }

        override removeDocument = (docIn: Doc | Doc[], annotationKey?: string, leavePushpin?: boolean, dontAddToRemoved?: boolean): boolean => {
            const effectiveAcl = GetEffectiveAcl(this.dataDoc);
            const docs = toList(docIn).filter(fdoc => [AclEdit, AclAdmin].includes(effectiveAcl) || GetEffectiveAcl(fdoc) === AclAdmin);

            // docs.forEach(doc => doc.annotationOn === this.Document && Doc.SetInPlace(doc, 'annotationOn', undefined, true));
            const targetDataDoc = this.Document[DocData]; // this.dataDoc;  // we want to write to the template, not the actual data doc
            const value = DocListCast(targetDataDoc[annotationKey ?? this.annotationKey]);
            const toRemove = value.filter(v => docs.includes(v));

            if (toRemove.length !== 0) {
                const recentlyClosed = this.Document !== Doc.MyRecentlyClosed ? Doc.MyRecentlyClosed : undefined;
                toRemove.forEach(rdoc => {
                    // leavePushpin && DocUtils.LeavePushpin(doc, annotationKey ?? this.annotationKey);
                    Doc.RemoveDocFromList(targetDataDoc, annotationKey ?? this.annotationKey, rdoc, true);
                    rdoc.embedContainer = undefined;
                    if (recentlyClosed && !dontAddToRemoved && rdoc.type !== DocumentType.LOADING) {
                        Doc.AddDocToList(recentlyClosed, 'data', rdoc, undefined, true, true);
                        Doc.RemoveEmbedding(rdoc, rdoc);
                    }
                });
                this.isAnyChildContentActive() && this._props.select(false);
                return true;
            }

            return false;
        };
        // this is called with the document that was dragged and the collection to move it into.
        // if the target collection is the same as this collection, then the move will be allowed.
        // otherwise, the document being moved must be able to be removed from its container before
        // moving it into the target.
        moveDocument = (docs: Doc | Doc[], targetCollection: Doc | undefined, addDocument: (doc: Doc | Doc[], annotationKey?: string) => boolean, annotationKey?: string): boolean => {
            if (Doc.AreProtosEqual(this._props.Document, targetCollection)) {
                return true;
            }
            const first = toList(docs)[0];
            if (!first?._dragOnlyWithinContainer && addDocument !== returnFalse) {
                return this.removeDocument(docs, annotationKey, false, true) && addDocument(docs, annotationKey);
            }
            return false;
        };

        override addDocument = (docIn: Doc | Doc[], annotationKey?: string): boolean => {
            const docs = toList(docIn);
            if (this._props.filterAddDocument?.(docs) === false || docs.find(fdoc => Doc.AreProtosEqual(fdoc, this.Document) && Doc.LayoutField(fdoc) === Doc.LayoutField(this.Document))) {
                return false;
            }
            const targetDataDoc = this.Document[DocData]; // this.dataDoc;  // we want to write to the template, not the actual data doc
            const effectiveAcl = GetEffectiveAcl(targetDataDoc);

            if (effectiveAcl === AclPrivate || effectiveAcl === AclReadonly) {
                return false;
            }
            const added = docs;
            if (added.length) {
                if ([AclAugment, AclEdit, AclAdmin].includes(effectiveAcl)) {
                    added.forEach(adoc => {
                        adoc._dragOnlyWithinContainer = undefined;
                        adoc.$annotationOn = (annotationKey ?? this._annotationKeySuffix()) ? this.Document : undefined;
                        Doc.SetContainer(adoc, this.Document);
                        inheritParentAcls(targetDataDoc, adoc, true);
                    });

                    const annoDocs = Doc.Get(targetDataDoc, annotationKey ?? this.annotationKey, true) as List<Doc>; // get the dataDoc directly ... when using templates there may be some default items already there, but we can't change them, so we copy them below (should really be some kind of inheritance since the template contents could change)
                    if (annoDocs instanceof List) annoDocs.push(...added.filter(add => !annoDocs.includes(add)));
                    else targetDataDoc[annotationKey || this.annotationKey] = new List<Doc>([...added, ...(annoDocs === undefined ? DocListCast(targetDataDoc[annotationKey ?? this.annotationKey]) : [])]);
                    targetDataDoc[(annotationKey ?? this.annotationKey) + '_modificationDate'] = new DateField();
                }
            }
            return true;
        };

        isAnyChildContentActive = () => this._isAnyChildContentActive;

        whenChildContentsActiveChanged = action((isActive: boolean) => {
            this._isAnyChildContentActive = isActive;
            this._props.whenChildContentsActiveChanged(isActive);
        });
    }
    return Component;
}
