'use strict';

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

const MOUSE_LEFT = 0;

export class ListRow extends React.Component<any> {
    static defaultProps = {
        children: null,
        testAutomationId: 'row',
        onClick: null,
        keyDownableProps: {
            preventDefaultKeyDown: false,
            preventDefaultMouseDown: false
        }
    };

    static propTypes = {
        children: PropTypes.node,
        testAutomationId: PropTypes.string,
        onClick: PropTypes.func,
        keyDownableProps: PropTypes.shape({
            preventDefaultKeyDown: PropTypes.bool,
            preventDefaultMouseDown: PropTypes.bool
        })
    };

    renderRow = ({onClick, onKeyDown, onMouseDown}) => {
        let {children, testAutomationId, ...props} = this.props;

        const onRowClick = e => {
            if (window.getSelection().toString().length > 0) {
                return;
            }
            onClick(e);
        };
        const onRowMouseDown = e => {
            if (e.button === MOUSE_LEFT) {
                window.getSelection().removeAllRanges();
            }
            onMouseDown(e);
        };
        return (
            <tr
                data-test-automation-id={testAutomationId}
                {..._.omit(props, ['keyDownableProps', 'onClick'])}
                onClick={onRowClick}
                onKeyDown={onKeyDown}
                onMouseDown={onRowMouseDown}>
                {children}
            </tr>
        );
    };

    render() {
        const {keyDownableProps, onClick} = this.props;
        return (
            <KeyDownable {...keyDownableProps} onClick={onClick}>
                {this.renderRow}
            </KeyDownable>
        );
    }
}
