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

export class ExternalLink extends React.Component {
    static propTypes = {
        tabIndex: PropTypes.number,
        id: PropTypes.string.isRequired,
        title: PropTypes.string.isRequired,
        href: PropTypes.string.isRequired,
        role: PropTypes.string,
        onClick: PropTypes.func,
        onKeyDown: PropTypes.func,
        withIcon: PropTypes.bool
    };

    static defaultProps = {
        tabIndex: -1,
        onClick: null,
        onKeyDown: null,
        role: null,
        withIcon: false
    };

    onClick = e => {
        if (_.isFunction(this.props.onClick)) {
            this.props.onClick(e);
        }
        return false;
    };

    /*
      Add onKeyDown event handler for <ExternalLink/> Component,
      For child element of <NavDropdown/> Component should receive onKeyDown prop from parent and bind to proper element.
     */
    onKeyDown = e => {
        if (_.isFunction(this.props.onKeyDown)) {
            this.props.onKeyDown(e);
        }
    };

    render() {
        const {id, href, tabIndex, title, role, withIcon} = this.props;
        const icon = withIcon ? <Icon name="link" /> : null;

        return (
            <li id={id} role="presentation" data-test-automation-id={id}>
                <a
                    href={href}
                    role={role}
                    tabIndex={tabIndex}
                    onClick={this.onClick}
                    onKeyDown={this.onKeyDown}
                    target="_blank"
                    className="link-item">
                    {title}
                    {icon}
                </a>
            </li>
        );
    }
}
