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

import PaginationUtil from '../../util/PaginationUtil';
import IDUtil from '../../util/IDUtil';
import ComponentUtil from '../../util/ComponentUtil';
import FlexRouter from '../../util/FlexRouter';

import { SINGLE_SEARCH_RESOURCE_VIEWER_POPUP } from '../../SingleSearchRecipe';
import LocalStorageHandler from '../../util/LocalStorageHandler';

export default class SimplePaging extends React.Component {
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        document.addEventListener('keydown', this.onKeyPressed);
    }

    componentWillUnmount() {
        document.removeEventListener('keydown', this.onKeyPressed);
    }

    onKeyPressed = e => {
        //use arrows in quickviewer, but not in resource viewer
        const renderInfo = PaginationUtil.getSearchResultRenderInfo(
            this.props.searchResult
        );
        const goNext = this.props.enableResourceViewerButton ?
            e.keyCode === 39 : //arrow right
            e.shiftKey && e.keyCode === 221 //shift+]
        ;
        const goPrev = this.props.enableResourceViewerButton ?
            e.keyCode === 37 : //arrow left
            e.shiftKey && e.keyCode === 219 //shift+[
        ;
        if (goNext && !renderInfo.isLastHit) {
            ComponentUtil.checkFocusAndExec.call(this, this.next);
        }

        if (goPrev && !renderInfo.isFirstHit) {
            ComponentUtil.checkFocusAndExec.call(this, this.previous);
        }

        //go back to results (resource viewer only)
        if (this.props.enableBackButton && e.keyCode === 8) { //backspace
            ComponentUtil.checkFocusAndExec.call(this, this.backToSearch);
        }

        //select current hit (quick viewer only)
        if (this.props.onSelect && e.keyCode === 83) { //s
            ComponentUtil.checkFocusAndExec.call(this, this.select);
        }

        //goto resource viewer (quick viewer only)
        if (this.props.enableResourceViewerButton && e.keyCode === 71) { //g
            ComponentUtil.checkFocusAndExec.call(this, this.gotoResourceViewer);
        }
    };

    /* ---------------------------------------- BUTTON HANDLING FUNCTIONS --------------------------------- */

    previous = () => {
        if (this.props.browseSelection) {
            PaginationUtil.pageSelections(
                this.props.searchResult,
                false,
                this.props.onPaged
            );
        } else {
            PaginationUtil.pageSearchResults(
                this.props.searchResult,
                this.props.collectionConfig,
                false,
                this.props.onPaged,
                this.props.onLoading
            );
        }
    };

    next = () => {
        if (this.props.browseSelection) {
            PaginationUtil.pageSelections(
                this.props.searchResult,
                true,
                this.props.onPaged
            );
        } else {
            PaginationUtil.pageSearchResults(
                this.props.searchResult,
                this.props.collectionConfig,
                true,
                this.props.onPaged,
                this.props.onLoading
            );
        }
    };

    select = () => {
        if (this.props.onSelect && typeof this.props.onSelect === 'function') {
            this.props.onSelect(this.props.searchResult, !this.props.selected);
        }
    };

    gotoResourceViewer = () => {
        const storedResults = LocalStorageHandler.getJSONFromLocalStorage(
            'stored-search-results'
        );
        FlexRouter.popupResourceViewer(
            '/tool/resource-viewer', //TODO get this path from the recipe params
            this.props.searchResult,
            storedResults ? storedResults.query.term : null,
            SINGLE_SEARCH_RESOURCE_VIEWER_POPUP
        );
    };

    backToSearch = () => FlexRouter.gotoSingleSearch('cache');

    //render based on
    render() {
        const renderInfo = this.props.browseSelection
            ? PaginationUtil.getSelectionsRenderInfo(this.props.searchResult)
            : PaginationUtil.getSearchResultRenderInfo(this.props.searchResult);

        const previousResourceBtn = (
            <button
                className="btn btn-primary"
                disabled={renderInfo.isFirstHit}
                onClick={this.previous}
            >
                <i
                    className="glyphicon glyphicon-step-backward"
                    aria-hidden="true"
                />{' '}
                Previous resource
            </button>
        );
        const nextResourceBtn = (
            <button
                className="btn btn-primary"
                disabled={renderInfo.isLastHit}
                onClick={this.next}
            >
                Next resource{' '}
                <i
                    className="glyphicon glyphicon-step-forward"
                    aria-hidden="true"
                />
            </button>
        );

        const selectBtn = this.props.onSelect ? (
            <div className="checkbox">
                <label>
                    <input
                        type="checkbox"
                        checked={this.props.selected}
                        onChange={this.select}
                    />
                    &nbsp;Select item
                </label>
            </div>
        ) : null;

        const backToSearchBtn = this.props.enableBackButton ? (
            <button className="btn btn-primary" onClick={this.backToSearch}>
                Back to results
            </button>
        ) : null;

        const gotoResourceViewerBtn = this.props.enableResourceViewerButton ? (
            <button
                className="btn btn-primary"
                onClick={this.gotoResourceViewer}
            >
                Open resource{' '}
                <i
                    className="glyphicon glyphicon-new-window"
                    aria-hidden="true"
                />
            </button>
        ) : null;

        return (
            <div className={IDUtil.cssClassName('simple-paging')}>
                {selectBtn}
                {previousResourceBtn}
                {nextResourceBtn}
                {backToSearchBtn}
                {gotoResourceViewerBtn}
            </div>
        );
    }
}

SimplePaging.propTypes = {
    browseSelection: PropTypes.bool.isRequired, //whether to quick view the selection or result list
    searchResult: PropTypes.object.isRequired, //active resource from either the selection or result list
    collectionConfig: PropTypes.object.isRequired,

    onPaged: PropTypes.func.isRequired, // called after each time paging is called
    onLoading: PropTypes.func.isRequired, //callback to notify the owner new search results are being fetched

    selected: PropTypes.bool, //whether the current resource is selected or not
    onSelect: PropTypes.func, //callback when selecting this resource

    enableBackButton: PropTypes.bool,
    enableResourceViewerButton: PropTypes.bool
};
