import React from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';
import {KeyCodes} from '../../utils/constants';

export class KeyDownable extends React.Component {
    static propTypes = {
        children: PropTypes.func.isRequired,
        preventDefaultKeyDown: PropTypes.bool,
        preventDefaultMouseDown: PropTypes.bool,
        tabIndex: PropTypes.number,
        stopPropagation: PropTypes.bool,
        onClick: PropTypes.func,
        onKeyDown: PropTypes.func,
        onMouseDown: PropTypes.func
    };

    static defaultProps = {
        preventDefaultKeyDown: true,
        preventDefaultMouseDown: true,
        tabIndex: 0,
        stopPropagation: false,
        onClick: null,
        onKeyDown: null,
        onMouseDown: null
    };

    onClick = e => {
        const {onClick} = this.props;

        if (_.isFunction(onClick)) {
            onClick(e);
        }
    };

    onKeyDown = e => {
        const {preventDefaultKeyDown, stopPropagation, onKeyDown} = this.props;

        if (_.isFunction(onKeyDown)) {
            return onKeyDown(e);
        }

        if (e.keyCode === KeyCodes.SPACE || e.keyCode === KeyCodes.ENTER) {
            if (preventDefaultKeyDown) {
                e.preventDefault();
            }

            if (stopPropagation) {
                e.stopPropagation();
            }

            this.onClick(e);
        }
    };

    /* prevent focus style always there after click */
    onMouseDown = e => {
        const {preventDefaultMouseDown, onMouseDown} = this.props;

        if (preventDefaultMouseDown) {
            e.preventDefault();
        }

        if (_.isFunction(onMouseDown)) {
            onMouseDown(e);
        }
    };

    render() {
        const {children: renderChild} = this.props;

        return renderChild({
            tabIndex: this.props.tabIndex,
            onClick: this.onClick,
            onKeyDown: this.onKeyDown,
            onMouseDown: this.onMouseDown
        });
    }
}
