
import _ from 'lodash';

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

import { FormattedMessage } from 'react-intl';

import DocumentAnnotations from './DocumentAnnotations';

const AnnotationsCards = ({
  annotations,
  viaBaseUrl,
  metacategories,
  categories,
  children,
}) => {
  const documents = _(annotations).groupBy('uri');

  const documentAnnotations = documents.map((docAnnotations, uri) => {
    const document = {
      uri,
      title: docAnnotations[0].document.title,
      annotations: docAnnotations,
    };

    return (
      <DocumentAnnotations
        key={document.uri}
        document={document}
        viaBaseUrl={viaBaseUrl}
        metacategories={metacategories}
        categories={categories}
      />
    );
  }).value();

  let noAnnotationContent = <FormattedMessage id="ui.annotationsCards.noAnnotation" defaultMessage="No annotation" />;
  if (React.Children.count(children) > 0) {
    noAnnotationContent = children;
  }

  return (
    <div className="card-columns">
      { annotations.length === 0 ? noAnnotationContent : documentAnnotations }
    </div>
  );
};

AnnotationsCards.propTypes = {
  annotations: PropTypes.arrayOf(PropTypes.object),
  viaBaseUrl: PropTypes.string.isRequired,
  metacategories: PropTypes.arrayOf(PropTypes.object).isRequired,
  categories: PropTypes.arrayOf(PropTypes.string).isRequired,
  children: PropTypes.node,
};

AnnotationsCards.defaultProps = {
  annotations: [],
  children: null,
};

export default AnnotationsCards;
