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';

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

        this.renderInfo = PaginationUtil.getSearchResultRenderInfo(
            this.props.searchResult
        );
    }

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

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

    onKeyPressed = e => {
        if (e.shiftKey && e.keyCode === 221 && !this.renderInfo.isLastHit) { //shift+]
            ComponentUtil.checkFocusAndExec.call(this, this.next);
        }
        if (e.shiftKey && e.keyCode === 219 && !this.renderInfo.isFirstHit) { //shift+[
            ComponentUtil.checkFocusAndExec.call(this, this.previous);
        }
    };

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

    previous = () => {
        PaginationUtil.pageSearchResults(
            this.props.searchResult,
            this.props.collectionConfig,
            false,
            this.props.onPaged,
            () => {}
        );
    };

    next = () => {
        PaginationUtil.pageSearchResults(
            this.props.searchResult,
            this.props.collectionConfig,
            true,
            this.props.onPaged,
            () => {}
        );
    };

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

    //render based on
    render() {
        const previousResourceBtn = (
            <button
                className="btn prev"
                disabled={this.renderInfo.isFirstHit}
                onClick={this.previous}
            >
                Previous resource
            </button>
        );

        const nextResourceBtn = (
            <button
                className="btn next"
                disabled={this.renderInfo.isLastHit}
                onClick={this.next}
            >
                Next resource
            </button>
        );

        const backToSearchBtn = (
            <button className="btn" onClick={this.backToSearch}>
                Back to results
            </button>
        );

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

Paging.propTypes = {
    searchResult: PropTypes.object.isRequired,
    collectionConfig: PropTypes.object.isRequired,
    onPaged: PropTypes.func.isRequired
};
