import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { IconButton, Size } from 'browndash-components';
import * as faceapi from 'face-api.js';
import { FaceMatcher } from 'face-api.js';
import 'ldrs/ring';
import { action, makeObservable, observable } from 'mobx';
import { observer } from 'mobx-react';
import React from 'react';
import { setupMoveUpEvents } from '../../../../ClientUtils';
import { Utils, emptyFunction } from '../../../../Utils';
import { Doc, Opt } from '../../../../fields/Doc';
import { Id } from '../../../../fields/FieldSymbols';
import { List } from '../../../../fields/List';
import { ImageCast } from '../../../../fields/Types';
import { DocumentType } from '../../../documents/DocumentTypes';
import { Docs } from '../../../documents/Documents';
import { DragManager } from '../../../util/DragManager';
import { dropActionType } from '../../../util/DropActionTypes';
import { SnappingManager } from '../../../util/SnappingManager';
import { undoable } from '../../../util/UndoManager';
import { ViewBoxBaseComponent } from '../../DocComponent';
import { ObservableReactComponent } from '../../ObservableReactComponent';
import { DocumentView } from '../../nodes/DocumentView';
import { FieldView, FieldViewProps } from '../../nodes/FieldView';
import { FaceRecognitionHandler } from '../../search/FaceRecognitionHandler';
import './FaceCollectionBox.scss';
import { MarqueeOptionsMenu } from './MarqueeOptionsMenu';

/**
 * This code is used to render the sidebar collection of unique recognized faces, where each
 * unique face in turn displays the set of images that correspond to the face.
 */

interface UniqueFaceProps {
    faceDoc: Doc;
}

/**
 * React component for rendering a unique face and its collection of image Docs.
 *
 * This both displays a collection of images corresponding tp a unique face, and
 * allows for editing the face collection by removing an image, or drag-and-dropping
 * an image that was not recognized.
 */
@observer
export class UniqueFaceView extends ObservableReactComponent<UniqueFaceProps> {
    private _dropDisposer?: DragManager.DragDropDisposer;

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

    @observable _displayImages: boolean = true;

    protected createDropTarget = (ele: HTMLDivElement) => {
        this._dropDisposer?.();
        ele && (this._dropDisposer = DragManager.MakeDropTarget(ele, this.onInternalDrop.bind(this), this._props.faceDoc));
    };

    protected onInternalDrop(e: Event, de: DragManager.DropEvent): boolean {
        de.complete.docDragData?.droppedDocuments
            ?.filter(doc => doc.type === DocumentType.IMG)
            .forEach(imgDoc => {
                // If the current Face Document has no faces, and the doc has more than one face descriptor, don't let the user add the document first.  Or should we just use the first face ?
                if (FaceRecognitionHandler.UniqueFaceDescriptors(this._props.faceDoc).length === 0 && FaceRecognitionHandler.ImageDocFaceDescriptors(imgDoc).length > 1) {
                    alert('Cannot add a document with multiple faces as the first item!');
                } else {
                    // Loop through the documents' face descriptors and choose the face in the iage with the smallest distance (most similar to the face colleciton)
                    const faceDescriptorsAsFloat32Array = FaceRecognitionHandler.UniqueFaceDescriptors(this._props.faceDoc).map(fd => new Float32Array(Array.from(fd)));
                    const labeledFaceDescriptor = new faceapi.LabeledFaceDescriptors(FaceRecognitionHandler.UniqueFaceLabel(this._props.faceDoc), faceDescriptorsAsFloat32Array);
                    const faceMatcher = new FaceMatcher([labeledFaceDescriptor], 1);
                    const { face_match } = FaceRecognitionHandler.ImageDocFaceDescriptors(imgDoc).reduce(
                        (prev, face) => {
                            const match = faceMatcher.matchDescriptor(new Float32Array(Array.from(face)));
                            return match.distance < prev.dist ? { dist: match.distance, face_match: face } : prev;
                        },
                        { dist: 1, face_match: new List<number>() as Opt<List<number>> }
                    );

                    // assign the face in the image that's closest to the face collection to be the face that's assigned to the collection
                    if (face_match) {
                        FaceRecognitionHandler.ImageDocAssociateUniqueFace(imgDoc, face_match, this._props.faceDoc);
                        FaceRecognitionHandler.UniqueFaceAddFaceImage(imgDoc, face_match, this._props.faceDoc);
                    }
                }
            });
        return false;
    }

    /**
     * Toggles whether a Face Document displays its associated docs.
     */
    @action
    onDisplayClick() {
        this._displayImages = !this._displayImages;
    }

    /**
     * Removes a unique face Doc from the colelction of unique faces.
     */
    deleteUniqueFace = undoable(() => {
        FaceRecognitionHandler.DeleteUniqueFace(this._props.faceDoc);
    }, 'delete face');

    /**
     * Removes a face image Doc from a unique face's list of images.
     * @param imgDoc - image Doc to remove
     */
    removeFaceImageFromUniqueFace = undoable((imgDoc: Doc) => {
        FaceRecognitionHandler.ImageDocDeassociateUniqueFace(imgDoc, this._props.faceDoc);
        FaceRecognitionHandler.UniqueFaceRemoveFaceImage(imgDoc, this._props.faceDoc);
    }, 'remove doc from face');

    render() {
        return (
            <div className="face-document-item" ref={ele => this.createDropTarget(ele!)}>
                <div className="face-collection-buttons">
                    <IconButton tooltip="Delete Face From Collection" onPointerDown={this.deleteUniqueFace} icon={'x'} style={{ width: '4px' }} size={Size.XSMALL} />
                </div>
                <div className="face-document-top">
                    <h1>{FaceRecognitionHandler.UniqueFaceLabel(this._props.faceDoc)}</h1>
                </div>
                <IconButton
                    tooltip="See image information"
                    onPointerDown={() => this.onDisplayClick()}
                    icon={<FontAwesomeIcon icon={this._displayImages ? 'caret-up' : 'caret-down'} />}
                    color={MarqueeOptionsMenu.Instance.userColor}
                    style={{ width: '19px' }}
                />
                {this._displayImages ? (
                    <div className="face-document-image-container">
                        {FaceRecognitionHandler.UniqueFaceImages(this._props.faceDoc).map(doc => {
                            const [name, type] = ImageCast(doc[Doc.LayoutFieldKey(doc)]).url.href.split('.');
                            return (
                                <div
                                    className="image-wrapper"
                                    key={Utils.GenerateGuid()}
                                    onPointerDown={e =>
                                        setupMoveUpEvents(
                                            this,
                                            e,
                                            () => {
                                                DragManager.StartDocumentDrag([e.target as HTMLElement], new DragManager.DocumentDragData([doc], dropActionType.embed), e.clientX, e.clientY);
                                                return true;
                                            },
                                            emptyFunction,
                                            emptyFunction
                                        )
                                    }>
                                    <img onClick={() => DocumentView.showDocument(doc, { willZoomCentered: true })} style={{ maxWidth: '60px', margin: '10px' }} src={`${name}_o.${type}`} />
                                    <div className="remove-item">
                                        <IconButton tooltip={'Remove Doc From Face Collection'} onPointerDown={() => this.removeFaceImageFromUniqueFace(doc)} icon={'x'} style={{ width: '4px' }} size={Size.XSMALL} />
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                ) : null}
            </div>
        );
    }
}

/**
 * This renders the sidebar collection of the unique faces that have been recognized.
 *
 * Since the collection of recognized faces is stored on the active dashboard, this class
 * does not itself store any Docs, but accesses the uniqueFaces field of the current
 * dashboard.  Each Face collection Doc is rendered using a FaceCollectionDocView which
 * is not a CollectionView or even a DocumentView (but probably should be).
 */
@observer
export class FaceCollectionBox extends ViewBoxBaseComponent<FieldViewProps>() {
    public static LayoutString(fieldKey: string) {
        return FieldView.LayoutString(FaceCollectionBox, fieldKey);
    }

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

    render() {
        return (
            <div className="searchBox-container" style={{ pointerEvents: 'all', color: SnappingManager.userColor, background: SnappingManager.userBackgroundColor }}>
                {FaceRecognitionHandler.UniqueFaces().map(doc => (
                    <UniqueFaceView key={doc[Id]} faceDoc={doc} />
                ))}
            </div>
        );
    }
}

Docs.Prototypes.TemplateMap.set(DocumentType.FACECOLLECTION, {
    layout: { view: FaceCollectionBox, dataField: 'data' },
    options: { acl: '', _width: 400 },
});
