import _ from 'lodash';

import { Component, PropTypes } from 'react';
import Avatar from '../aui-react/avatar';
import { ApprovalState } from '../models/models';

const propTypes = {
    avatarSize: PropTypes.string,
    reviewer: PropTypes.shape({
        user: PropTypes.object.isRequired,
        state: PropTypes.oneOf(_.values(ApprovalState)).isRequired,
    }).isRequired,
    withName: PropTypes.bool,
    tooltip: PropTypes.bool,
    nameOnly: PropTypes.bool,
};

const visibleBadgeCssClass = {
    APPROVED: 'approved',
    NEEDS_WORK: 'needs-work',
};

const avatarBadges = [{
    className: visibleBadgeCssClass.APPROVED,
    text: AJS.I18n.getText('bitbucket.component.avatar.badge.approved'),
}, {
    className: visibleBadgeCssClass.NEEDS_WORK,
    text: AJS.I18n.getText('bitbucket.component.avatar.badge.needs.work'),
}];

function reviewerTooltip(reviewer, nameOnly) {
    const name = reviewer.user.display_name || reviewer.user.name;
    let displayText;
    if (nameOnly || !reviewer.state || reviewer.state === ApprovalState.UNAPPROVED) {
        displayText = name;
    } else if (reviewer.state === ApprovalState.APPROVED) {
        displayText = AJS.I18n.getText('bitbucket.component.pull.request.reviewer.tooltip.approved', name);
    } else {
        displayText = AJS.I18n.getText('bitbucket.component.pull.request.reviewer.tooltip.needs.work', name);
    }
    return displayText;
}

class ReviewerAvatar extends Component {
    shouldComponentUpdate(newProps) {
        return this.props.reviewer.user.name !== newProps.reviewer.user.name ||
            this.props.reviewer.state !== newProps.reviewer.state ||
            this.props.avatarSize !== newProps.avatarSize ||
            Boolean(this.props.nameOnly) !== Boolean(newProps.nameOnly) ||
            Boolean(this.props.tooltip) !== Boolean(newProps.tooltip) ||
            Boolean(this.props.withName) !== Boolean(newProps.withName);
    }

    render() {
        const props = this.props;
        return (
            <Avatar
                person={props.reviewer.user}
                size={props.avatarSize}
                badges={avatarBadges}
                tooltipText={reviewerTooltip(props.reviewer, props.nameOnly)}
                visibleBadge={props.reviewer.state ? visibleBadgeCssClass[props.reviewer.state] : ''}
                withName={props.withName}
                tooltip={props.tooltip}
            />
        );
    }
}

ReviewerAvatar.propTypes = propTypes;
export default ReviewerAvatar;
