import AJS from 'aui';
import classNames from 'classnames';
import { Component, PropTypes } from 'react';
import { findDOMNode } from 'react-dom';

import { ProjectAvatar } from '../aui-react/avatar';

const propTypes = {
    fromRef: PropTypes.object.isRequired,
    toRef: PropTypes.object.isRequired,
};

class BranchFromTo extends Component {

    componentDidMount() {
        const node = findDOMNode(this);
        AJS.$('.ref-name', node).tooltip();
    }

    componentWillUnmount() {
        const node = findDOMNode(this);
        AJS.$('.ref-name', node).tooltip('destroy');
    }

    refItem(ref, type, sameProject, sameRepo) {
        const showProject = !sameProject;
        const showRepo = sameProject && !sameRepo;
        const avatar = this.projectAvatar(ref, showProject);

        return (
            <div className={classNames('ref-name', 'ref-name-' + type, { 'with-avatar': avatar })} title={this.refTitle(ref)}>
                {avatar}
                {this.displayTitle(ref, showRepo)}
            </div>
        );
    }

    projectAvatar(ref, differentProject) {
        if (differentProject) {
            return (
                <span className="avatar-to-project avatar-ref-project">
                    <ProjectAvatar
                        size="xsmall"
                        project={ref.repository.project}
                        tagName="span"
                    />
                </span>
            );
        }
    }

    displayTitle(ref, showRepo) {
        if (showRepo) {
            return (
                <span>
                    <span className="repo-name">{ref.repository.name}</span>
                    <span className="repo-name-icon"></span>
                    <span className="branch-name">{ref.display_id}</span>
                </span>
            );
        }
        return <span className="branch-name">{ref.display_id}</span>;
    }

    refTitle(ref) {
        return `${ref.repository.project.name} / ${ref.repository.name} / ${ref.display_id}`;
    }

    render() {
        const { fromRef, toRef } = this.props;
        const sameProject = fromRef.repository.project.id === toRef.repository.project.id;
        const sameRepo = fromRef.repository.id === toRef.repository.id;

        return (
            <div className="branch-from-to">
                {this.refItem(fromRef, 'from', sameProject, sameRepo)}

                <div className="aui-icon aui-icon-small aui-iconfont-devtools-arrow-right arrow">to</div>

                {this.refItem(toRef, 'to', sameProject, sameRepo)}
            </div>
        );
    }
}

BranchFromTo.propTypes = propTypes;

export default BranchFromTo;
