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

import IDUtil from '../../util/IDUtil';
import SearchSnippet from './SearchSnippet';
import ReactTooltip from 'react-tooltip';
import LocalStorageHandler from '../../util/LocalStorageHandler';

class SearchHit extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            previewMode: false
        };
        this.CLASS_PREFIX = 'sh';
    }

    safeModalId() {
        return (
            this.CLASS_PREFIX +
            Math.floor(Math.random() * 10000 + 1) +
            '__modal'
        );
    }

    select(e) {
        e.stopPropagation();
        if (this.props.onOutput) {
            this.props.onOutput(this.constructor.name, {
                resource: this.props.searchResult,
                selected: !this.props.isSelected
            });
        }
    }

    renderToolTipContent() {
        if (!this.props.bookmark) {
            return null;
        }
        let html = '';
        if (
            this.props.bookmark.groups &&
            this.props.bookmark.groups.length > 0
        ) {
            html += '<h5><u>Bookmark group(s)</u>:</h5><ul>';
            html += this.props.bookmark.groups
                .map(group =>
                    group.label ? '<li>' + group.label + '</li>' : ''
                )
                .join('');
            html += '</ul>';
        }
        let bodyCount = 0;
        if (this.props.bookmark.annotations) {
            bodyCount += this.props.bookmark.annotations.length;
        }
        if (this.props.bookmark.segments) {
            this.props.bookmark.segments.forEach(
                segment =>
                    (bodyCount += segment.annotations
                        ? segment.annotations.length
                        : 0)
            );
        }
        html += '<h5><u>Annotations</u>: ' + bodyCount + '</h5>';
        return html;
    }

    onQuickView() {
        if (this.props.onQuickView) {
            this.props.onQuickView(this.props.searchResult, false, false); //FIXME the booleans for first & last quickview hit should be calculated!
        }
    }

    render() {
        //FIXME make sure that this snippet already contains the highlight data!
        const snippet = this.props.collectionConfig.getResultSnippetData(
            this.props.searchResult,
            this.props.searchResult.numHighlights,
            this.props.query.term
        );

        const modalID = this.safeModalId(this.props.searchResult.resourceId);

        //draw the checkbox using the props.isSelected to determine whether it is selected or not
        const checkBox = (
            <div className={IDUtil.cssClassName('select', this.CLASS_PREFIX)}>
                <input
                    type="checkbox"
                    onChange={this.select.bind(this)}
                    checked={this.props.isSelected}
                    id={'cb__' + modalID}
                    key={modalID}
                />
                <label htmlFor={'cb__' + modalID}>
                    <span />
                </label>
            </div>
        );

        const classNames = [IDUtil.cssClassName('search-hit')];

        // media fragment
        if (snippet.type === 'media_fragment') {
            classNames.push('fragment');
        }

        // visited
        let visitedIcon = null;
        if (this.props.visited) {
            classNames.push('visitedItem');
            visitedIcon = (
                <div
                    className={IDUtil.cssClassName(
                        'visited-icon',
                        this.CLASS_PREFIX
                    )}
                    title="Visited"
                />
            );
        }

        // bookmarked
        let bookmarkIcon = null;
        if (this.props.bookmark) {
            classNames.push('bookmarked');

            //draw an icon with tooltip if this item was bookmarked
            bookmarkIcon = (
                <div
                    data-for={'__qb__tt' + this.props.bookmark.id}
                    data-tip={this.renderToolTipContent(this)}
                    data-html={true}
                    className={IDUtil.cssClassName(
                        'bookmarked',
                        this.CLASS_PREFIX
                    )}
                >
                    <i className="fa fa-bookmark" />
                    <ReactTooltip id={'__qb__tt' + this.props.bookmark.id} />
                </div>
            );
        } else {
            // TODO: It would be nice if the searchhit could be bookmarked directly, without selecting it
            bookmarkIcon = (
                <div
                    style={{ opacity: '0' }}
                    className={IDUtil.cssClassName(
                        'bookmarked',
                        this.CLASS_PREFIX
                    )}
                >
                    <i className="fa fa-bookmark" />
                </div>
            );
        }

        const quickViewButton = (
            <div
                className={IDUtil.cssClassName('quickview', this.CLASS_PREFIX)}
            >
                <button
                    className="btn btn-default"
                    onClick={this.onQuickView.bind(this)}
                    title="Quick view"
                >
                    <span className="fa fa-file-text" />
                </button>
            </div>
        );

        return (
            <div className={classNames.join(' ')}>
                {checkBox}
                {bookmarkIcon}
                {quickViewButton}
                {visitedIcon}

                <SearchSnippet
                    onClick={e =>
                        this.props.onGotoResourceViewer(
                            this.props.searchResult,
                            this.props.query,
                            e.shiftKey
                        )
                    }
                    data={snippet}
                    searchRegex={this.props.query.searchRegex}
                />
            </div>
        );
    }
}

SearchHit.propTypes = {
    searchResult: PropTypes.shape({
        highlights: PropTypes.object.isRequired,
        numHighlights: PropTypes.number.isRequired
    }).isRequired,

    //required for highlighting
    query: PropTypes.shape({
        searchRegex: PropTypes.object,
        term: PropTypes.string.isRequired
    }).isRequired,
    visited: PropTypes.bool, //whether this resource has been viewed in the resource viewer or not
    collectionConfig: PropTypes.object.isRequired,
    selectable: PropTypes.bool, //whether to add a selection box or not
    bookmark: PropTypes.object, //the bookmark object, containing all information for drawing the bookmark icon & icon tooltip
    isSelected: PropTypes.bool, //whether this hit is selected or not
    onGotoResourceViewer: PropTypes.func.isRequired, //go to the resource viewer when clicked
    onQuickView: PropTypes.func.isRequired, //what to do when the user clicks the clickview item
    onOutput: PropTypes.func.isRequired //outputs data to the owner after the user selects or deselects
};

export default SearchHit;
