import _ from 'lodash';
import { Component, PropTypes } from 'react';
import ReviewerAvatarList from '../../reviewer-avatar-list/reviewer-avatar-list';

const MAX_OPEN = 3;

function anyReviewersDifferent(oldReviewers, newReviewers) {
    return oldReviewers.length !== newReviewers.length ||
        _.zip(oldReviewers, newReviewers).some((a, b) =>
            a.name !== b.name || a.state !== b.state
        );
}

class Reviewers extends Component {
    static get propTypes() {
        return {
            currentUser: PropTypes.object,
            currentUserAvatarSize: PropTypes.string,
            dialogReviewersAsTooltip: ReviewerAvatarList.propTypes.dialogReviewersAsTooltip,
            pullRequest: PropTypes.object.isRequired,
        };
    }

    shouldComponentUpdate(newProps) {
        return this.props.pullRequest.id !== newProps.pullRequest.id ||
            anyReviewersDifferent(this.props.pullRequest.reviewers, newProps.pullRequest.reviewers) ||
            this.props.pullRequest.state !== newProps.pullRequest.state;
    }

    render() {
        const pullRequest = this.props.pullRequest;

        return (
            <td className="reviewers">
                <ReviewerAvatarList
                    avatarSize="small"
                    currentUserAsReviewer={this.props.currentUser}
                    currentUserAvatarSize={this.props.currentUserAvatarSize}
                    dialogReviewersAsTooltip={this.props.dialogReviewersAsTooltip}
                    maxOpen={MAX_OPEN}
                    menuId={'reviewers-' + pullRequest.id}
                    permissionToReview={false}
                    pullRequestIsOpen={pullRequest.state === 'OPEN'}
                    reviewers={pullRequest.reviewers}
                />
            </td>
        );
    }
}

Reviewers.Header = () => <th className="reviewers" scope="col">{AJS.I18n.getText('bitbucket.pull.request.table.title.reviewers')}</th>;

export default Reviewers;
