import { action, observable } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import { VideoField } from '../../../../fields/URLField';
import { Upload } from '../../../../server/SharedMediaTypes';
import { ViewBoxBaseComponent } from '../../DocComponent';
import { FieldView, FieldViewProps } from '../FieldView';
import { VideoBox } from '../VideoBox';
import { RecordingView } from './RecordingView';
import { DocumentType } from '../../../documents/DocumentTypes';
import { Presentation } from '../../../util/TrackMovements';
import { Doc, DocListCast } from '../../../../fields/Doc';
import { Id } from '../../../../fields/FieldSymbols';
import { BoolCast, Cast, DocCast } from '../../../../fields/Types';
import { ScriptingGlobals } from '../../../util/ScriptingGlobals';
import { DocumentManager } from '../../../util/DocumentManager';
import { Docs } from '../../../documents/Documents';
import { CollectionFreeFormView } from '../../collections/collectionFreeForm/CollectionFreeFormView';
import { CurrentUserUtils } from '../../../util/CurrentUserUtils';
import { DocumentView } from '../DocumentView';
import { SettingsManager } from '../../../util/SettingsManager';
import { PropertiesView } from '../../PropertiesView';
import { PropertiesSection } from '../../PropertiesSection';
import { PropertiesDocContextSelector } from '../../PropertiesDocContextSelector';
import { listSpec } from '../../../../fields/Schema';
import { DragManager } from '../../../util/DragManager';

@observer
export class RecordingBox extends ViewBoxBaseComponent<FieldViewProps>() {
    public static LayoutString(fieldKey: string) {
        return FieldView.LayoutString(RecordingBox, fieldKey);
    }

    private _ref: React.RefObject<HTMLDivElement> = React.createRef();

    componentDidMount() {
        this.props.setContentView?.(this);
        Doc.SetNativeWidth(this.dataDoc, 1280);
        Doc.SetNativeHeight(this.dataDoc, 720);
    }

    @observable result: Upload.AccessPathInfo | undefined = undefined;
    @observable videoDuration: number | undefined = undefined;

    @action
    setVideoDuration = (duration: number) => {
        this.videoDuration = duration;
    };

    @action
    setResult = (info: Upload.AccessPathInfo, presentation?: Presentation) => {
        this.result = info;
        this.dataDoc.type = DocumentType.VID;
        this.dataDoc[this.fieldKey + '_duration'] = this.videoDuration;

        this.dataDoc.layout = VideoBox.LayoutString(this.fieldKey);
        this.dataDoc[this.props.fieldKey] = new VideoField(this.result.accessPaths.client);
        this.dataDoc[this.fieldKey + '_recorded'] = true;
        // stringify the presentation and store it
        if (presentation?.movements) {
            const presCopy = { ...presentation };
            presCopy.movements = presentation.movements.map(movement => ({ ...movement, doc: movement.doc[Id] })) as any;
            this.dataDoc[this.fieldKey + '_presentation'] = JSON.stringify(presCopy);
        }
    };

    Record: undefined | (() => void);
    Pause: undefined | (() => void);
    Finish: undefined | (() => void);
    getControls = (record: () => void, pause: () => void, finish: () => void) => {
        this.Record = record;
        this.Pause = pause;
        this.Finish = finish;
    };

    render() {
        return (
            <div className="recordingBox" ref={this._ref}>
                {!this.result && (
                    <RecordingView
                        forceTrackScreen={BoolCast(this.layoutDoc[this.fieldKey + '_trackScreen'])}
                        getControls={this.getControls}
                        setResult={this.setResult}
                        setDuration={this.setVideoDuration}
                        id={DocCast(this.rootDoc.proto)?.[Id] || ''}
                    />
                )}
            </div>
        );
    }
    static screengrabber: RecordingBox | undefined;
}
ScriptingGlobals.add(function toggleRecording(_readOnly_: boolean) {
    console.log(_readOnly_)
    console.log(RecordingBox.screengrabber)
    if (_readOnly_) return RecordingBox.screengrabber ? true : false;
    if (RecordingBox.screengrabber) {
        //if recordingbox is true; when we press the stop button. changed vals temporarily to see if changes happening
        console.log('grabbing screen!')
        RecordingBox.screengrabber.Pause?.();
        const remDoc = RecordingBox.screengrabber.rootDoc;
        setTimeout(() => {
            RecordingBox.screengrabber?.Finish?.();
            RecordingBox.screengrabber!.rootDoc.overlayX = 400; //was 100
            RecordingBox.screengrabber!.rootDoc.overlayY = 100;
            // DocListCast(Doc.MyOverlayDocs.data)
            // .filter(doc => doc.slides === RecordingBox.screengrabber!.rootDoc)
            // .forEach(Doc.RemFromMyOverlay);
            console.log(RecordingBox.screengrabber)
            RecordingBox.screengrabber = undefined;
        }, 100);
        //could break if recording takes too long to turn into videobox. If so, either increase time on setTimeout below or find diff place to do this
        setTimeout(() => {
            Doc.RemFromMyOverlay(remDoc);

        }, 1000)
        Doc.UserDoc().isRecording = false;
        
        // Doc.AddDocToList(Doc.UserDoc(), "workspaceRecordings", RecordingBox.screengrabber.dataDoc);
        Doc.AddDocToList(Doc.UserDoc(), "workspaceRecordings", RecordingBox.screengrabber.rootDoc);
       
        // let recView = Array.from(DocumentManager.Instance.DocumentViews).find(view => view.ComponentView instanceof CollectionFreeFormView);
        // console.log(recView)
    } else {
        //when we first press mic
        const screengrabber = Docs.Create.WebCamDocument('', {
            _width: 384,
            _height: 216,
        });
        // Doc.UserDoc().currentScreenGrab = screengrabber;
        screengrabber.overlayX = 100; //was -400
        screengrabber.overlayY = 100; //was 0
        screengrabber[Doc.LayoutFieldKey(screengrabber) + '_trackScreen'] = true;
        Doc.AddToMyOverlay(screengrabber);  //just adds doc to overlay
        DocumentManager.Instance.AddViewRenderedCb(screengrabber, docView => {
            RecordingBox.screengrabber = docView.ComponentView as RecordingBox;
            RecordingBox.screengrabber.Record?.();
        });
        // Doc.AddDocToList(Doc.UserDoc(), "workspaceRecordings", screengrabber);
        Doc.UserDoc().isRecording = true;
        
    }
}, 'toggle recording');
ScriptingGlobals.add(function toggleRecPlayback(value: Doc) {
    let docval = undefined;
    Doc.UserDoc().isRecPlayback = true;
    Doc.UserDoc().currentRecording = value;
    console.log(value)
    value.overlayX = 100;
    value.overlayY = 100;
    if (!Doc.UserDoc().isAddRecToDocMode) {
    Doc.AddToMyOverlay(value);
        DocumentManager.Instance.AddViewRenderedCb(value, docView => {
            docval = 
            Doc.UserDoc().currentRecording = docView.ComponentView as VideoBox;
            // docval.Play();
    })} else {
        let recordingIndex = Array.from(Doc.UserDoc().workspaceRecordings).indexOf(value);
        DragManager.StartDropdownDrag([document.createElement('div')],new DragManager.DocumentDragData([value]), 1, 1, recordingIndex);
    
    }
    
    // let ffView = Array.from(DocumentManager.Instance.DocumentViews).find(view => view.ComponentView instanceof CollectionFreeFormView);
    // (ffView?.ComponentView as CollectionFreeFormView).props.addDocument?.(value);
});
ScriptingGlobals.add(function addRectoWorkspace(value: VideoBox) {
    console.log("adding rec to doc");
    console.log(value.rootDoc);
    Doc.UserDoc().isAddRecToDocMode = true;
    
    
})
ScriptingGlobals.add(function playWorkspaceRec(value: VideoBox) {
    value.Play();
})
ScriptingGlobals.add(function pauseWorkspaceRec(value: VideoBox) {
    value.Pause();
})
ScriptingGlobals.add(function closeWorkspaceRec(value: VideoBox) {
    value.Pause();
    Doc.RemFromMyOverlay(value.rootDoc);
    Doc.UserDoc().currentRecording = undefined;
    Doc.UserDoc().isRecPlayback = false;
})

ScriptingGlobals.add(function getWorkspaceRecordings() {
    return Doc.UserDoc().workspaceRecordings
});
ScriptingGlobals.add(function getIsRecording() {
    return Doc.UserDoc().isRecording;
})
ScriptingGlobals.add(function getIsRecPlayback() {
    return Doc.UserDoc().isRecPlayback;
})
ScriptingGlobals.add(function getCurrentRecording() {
    return Doc.UserDoc().currentRecording;  
})


