import React from "react";
import PropTypes from "prop-types";

import IDUtil from "../../util/IDUtil"; // for generating unique CSS classnames for this component
import SessionStorageHandler from "../../util/SessionStorageHandler";
import BookmarkUtil from "../../util/BookmarkUtil";
import ComponentUtil from "../../util/ComponentUtil";

import MediaEvents from "./_MediaEvents";
import AnnotationColumn from "./AnnotationColumn";
import AnnotationPopup from "./AnnotationPopup";
import MediaColumn from "./MediaColumn";
import StaticColumn from "./StaticColumn";
import ViewerHeader from "./ViewerHeader";
import {
    COLUMN_STATIC,
    COLUMN_ANNOTATIONS,
    SESSION_STORAGE_COLUMNS,
} from "./BaseColumn";

// bookmark selector
import FlexModal from "../FlexModal";
import BookmarkSelector from "../bookmark/BookmarkSelector";
import QuickEntityViewer from '../../components/search/QuickEntityViewer';

import { ResourceViewerContext } from "./ResourceViewerContext";

/*
	This component contains the main UI elements for the resource viewer
*/

export default class ViewerBase extends React.Component {
    static contextType = ResourceViewerContext;

    constructor(props) {
        super(props);

        this.CLASS_PREFIX = "VB";

        this.state = {
            // default column visibility
            [COLUMN_STATIC]:
                SessionStorageHandler.getInt(
                    SESSION_STORAGE_COLUMNS[COLUMN_STATIC],
                    1
                ) == 1,
            [COLUMN_ANNOTATIONS]:
                SessionStorageHandler.getInt(
                    SESSION_STORAGE_COLUMNS[COLUMN_ANNOTATIONS],
                    1
                ) == 1,
            showBookmarkSelector: false,
			showMoreInfoModal : false, //for the moreinfo pop-up
            showAnnotationPopup: false,
        };
    }

    componentDidMount() {
        this.context.mediaEvents.bind(
            MediaEvents.SHOW_CONTENT_ANNOTATIONS,
            this.showColumnStatic
        );
    }

    componentWillUnmount() {
        this.context.mediaEvents.unbind(
            MediaEvents.SHOW_CONTENT_ANNOTATIONS,
            this.showColumnStatic
        );
    }

    /* ----------------------------- COLUMNS ------------------------ */

    showColumnStatic = () => {
        this.showColumn(COLUMN_STATIC);
    };

    showColumn = (columnId) => {
        this.setColumnVisibility(columnId, true);
    };

    toggleColumn = (columnId) => {
        this.setColumnVisibility(columnId, !this.state[columnId]);
    };

    setColumnVisibility = (columnId, visible) => {
        this.setState({ [columnId]: visible }, () => {
            // store state to session storage
            SessionStorageHandler.set(
                SESSION_STORAGE_COLUMNS[columnId],
                this.state[columnId] ? 1 : 0
            );
        });

        // trigger window resize, so things like timeline get resized
        setTimeout(() => {
            window.dispatchEvent(new Event("resize"));
        }, 300);
    };

    /* ----------------------------- ANNOTATION POPUP ------------------------ */

    showAnnotationPopup = () => {
        this.setState({ showAnnotationPopup: true });
    };

    hideAnnotationPopup = () => {
        this.setState({ showAnnotationPopup: false });
    };

    /* ----------------------------- BOOKMARK SELECTOR ------------------------ */

    // Render bookmark modal
    renderBookmarkModal = (userProjects, activeProject, itemData, user) => {
        return (
            <FlexModal
                elementId="bookmark__modal"
                stateVariable="showBookmarkModal"
                owner={this}
                size="large"
                title="Select one or more bookmark groups to associate the current resource with"
                onClose={this.hideBookmarkSelector}
            >
                <BookmarkSelector
                    onOutput={this.bookmarkSelection}
                    user={user}
                    project={activeProject}
                    userProjects={userProjects}
                    collectionId={itemData.index}
                    resourceId={itemData.resourceId}
                />
            </FlexModal>
        );
    };

    // Show the bookmark selector
    showBookmarkSelector = () => {
        this.setState({ showBookmarkSelector: true });
    };

    // Hide the bookmark selector
    hideBookmarkSelector = () => {
        this.setState({ showBookmarkSelector: false });
    };

    //show the more info pop-up about the selected entity (e.g. person)
    openMoreInfoModal = entityID => {
	    this.setState({
	        entityID: entityID,
			showMoreInfoModal : true
	    });
	};

    bookmarkSelection = (_, data) => {
        this.hideBookmarkSelector();

        // hide the modal
        ComponentUtil.hideModal(
            this,
            "showBookmarkModal",
            "bookmark__modal",
            true,
            () => {
                // put the complicated function in a new util
                // (not in the context, since it surpasses this context and could be used in other contexts as well)
                BookmarkUtil.bookmarkToGroupInProject(
                    this.context.resource.resourceId,
                    this.context.collectionConfig.getSearchIndex(),
                    data.allGroups,
                    data.selectedGroups,
                    () => {}
                );
            }
        );
    };

    /* ------------------------More info modal---------------------- */
    renderMoreInfoModal = (entityID, collectionConfig) => {
	    return (
	        <FlexModal
				elementId="moreinfo__modal"
				stateVariable="showMoreInfoModal"
				owner={this}
				size="medium"
				title={"Person information"}>
				<QuickEntityViewer
				    entityID = {entityID}
                    entityType = "person"//TODO should be variable
				    collectionConfig={this.context.collectionConfig}
				    fieldCategories = {[]}
				/>
			</FlexModal>
		)
	};

    /* ----------------------------- RENDER ------------------------ */



    render() {
        const bookmarkSelector = this.state.showBookmarkSelector
            ? this.renderBookmarkModal(
                  this.context.userProjects,
                  this.context.activeProject,
                  this.context.resource,
                  this.context.user
              )
            : null;


        const moreInfoModal = this.state.showMoreInfoModal && this.state.entityID ? this.renderMoreInfoModal(
			this.state.entityID,
			this.state.collectionConfig
        ) : null;

        return (
            <div className={IDUtil.cssClassName("viewer-base")}>
                <ViewerHeader
                    activeProject={this.context.activeProject}
                    userProjects={this.context.userProjects}
                    user={this.context.user}
                    resource={this.context.resource}
                    query={this.context.query}
                    showPaging={!this.context.singleResource}
                    collectionConfig={this.context.collectionConfig}
                    recipe={this.context.recipe}
                    onBookmark={this.showBookmarkSelector}
                    setActiveProject={this.context.setActiveProject}
                />

                <div className="columns">
                    <MediaColumn
                        mediaObjects={this.context.resource.playableContent || []}
                        transcripts={this.context.resource.transcripts || null}
                        showAnnotationPopup={this.showAnnotationPopup}
                    />

                    <StaticColumn
                        onToggle={this.toggleColumn}
                        active={this.state[COLUMN_STATIC]}
                        onMoreInfo={this.openMoreInfoModal}
                    />

                    {this.context.user &&
                        this.context.user.id !== "ANONYMOUS" && (
                            <AnnotationColumn
                                onToggle={this.toggleColumn}
                                active={this.state[COLUMN_ANNOTATIONS]}
                                showBookmarkSelector={this.showBookmarkSelector}
                            />
                        )}

                    {this.context.user &&
                        this.context.user.id !== "ANONYMOUS" &&
                        this.state.showAnnotationPopup && (
                            <AnnotationPopup
                                onClose={this.hideAnnotationPopup}
                                showBookmarkSelector={this.showBookmarkSelector}
                            />
                        )}
                </div>

                {bookmarkSelector}
                {moreInfoModal}
            </div>
        );
    }
}

ViewerBase.propTypes = {}; //just uses the ResourceViewerContext
