import _ from 'lodash';

import {
  RECEIVE_ANNOTATIONS,
} from '../actions';

function documents(
  state = {
    documents: {},
  },
  action,
) {
  switch (action.type) {
    case RECEIVE_ANNOTATIONS:
      return Object.assign({}, state, {
        documents: _(action.annotations)
          .groupBy('uri')
          .map((annotList, url) => {
            const users = _(annotList).map(a => a.user).uniq().value();
            const tagsCall = _(annotList)
              .reduce(
                (res, annot) => res.concat(annot.tags.filter(t => t.toLowerCase().startsWith('need:'))),
                [],
              );
            const commentsNb = _(annotList).reduce((res, annot) => {
              let fres = res;
              if (annot.references && annot.references.length) {
                fres += 1;
              }
              return fres;
            }, 0);
            return [
              url,
              {
                uri: url,
                annotations: annotList.length,
                users: users.length,
                calls: tagsCall.length,
                comments: commentsNb,
                updated: annotList[0].updated,
              },
            ];
          }).fromPairs()
          .value(),
      });

    default:
      return state;
  }
}

export default documents;
