import React from 'react';
import PropTypes from 'prop-types';

import IDUtil from '../../util/IDUtil';
import Project from '../../model/Project';
import classNames from 'classnames';
import ProjectList from '../search/ProjectList';

class ToolHeader extends React.PureComponent {

    constructor(props) {
        super(props);
        this.CLASS_PREFIX = 'th';
    }

    selectProject = project => {
        this.props.onOutput(this.constructor.name, project);
    };

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

        const title = (
            <h1 className={IDUtil.cssClassName('title', this.CLASS_PREFIX)}>
                {this.props.name}
            </h1>
        );

		//only render when the project list is populated, since the ProjectList component does not handle updated props yet! (FIXME)
		//&& this.props.projects.length > 0
		const projectBtn = this.props.onOutput && this.props.projects ? (
			<div
				className={classNames(
					IDUtil.cssClassName("project", this.CLASS_PREFIX),
					{ active: activeProject }
				)}
				title={activeProject ? "Current user project. Click to change." : ""}
			>
                <ProjectList
                    activeProject={this.props.activeProject}
                    onSelect={this.selectProject}
                    projects={this.props.projects}
                    user={this.props.user}
                />
			</div>
		) : null;

        const projectLink = this.props.activeProject ? (
            <a
                href={'/workspace/projects/' + activeProject.id}
                className={IDUtil.cssClassName(
                    'project-link',
                    this.CLASS_PREFIX
                )}
                title="Open project in new window"
                target="_blank"
            />
        ) : null;

        return (
            <div className={IDUtil.cssClassName('tool-header')}>
                {title}
                {projectLink}
                {projectBtn}
            </div>
        );
    }
}

ToolHeader.propTypes = {
    name: PropTypes.string.isRequired, // recipe name
    selectProject: PropTypes.func, // callback to select another project
    projects: PropTypes.array,
    onOutput: PropTypes.func,
    activeProject: Project.getPropTypes(false), // requires the selectProject function to be defined
    user: PropTypes.shape({
        id: PropTypes.string,
        name: PropTypes.string,
        attributes: PropTypes.shape({
            allowPersonalCollections: PropTypes.bool
        })
    })
};

export default ToolHeader;
