001package org.gbif.api.model.checklistbank;
002
003import org.gbif.api.vocabulary.Language;
004
005import java.util.List;
006import java.util.Map;
007
008import com.google.common.base.Objects;
009import com.google.common.base.Strings;
010import com.google.common.collect.Lists;
011import com.google.common.collect.Maps;
012import org.codehaus.jackson.annotate.JsonIgnore;
013
014/**
015 * A simple class to represent a table of contents for multiple languages.
016 * It is used by species pages to generate a table of contents menu with asynchronous loading of full descriptions.
017 */
018public class TableOfContents {
019  private static final String DEFAULT_TOPIC = "general";
020
021  private final Map<Language, Map<String, List<Integer>>> toc = Maps.newTreeMap();
022
023  public void addDescription(int key, Language lang, String topic) {
024    topic = Strings.isNullOrEmpty(topic) ? DEFAULT_TOPIC : topic.toLowerCase().trim();
025
026    if (lang == null) {
027      // default to english
028      lang = Language.ENGLISH;
029    }
030
031    if (!toc.containsKey(lang)) {
032      toc.put(lang, Maps.<String, List<Integer>>newTreeMap());
033    }
034    if (!toc.get(lang).containsKey(topic)) {
035      toc.get(lang).put(topic, Lists.<Integer>newArrayList());
036    }
037    toc.get(lang).get(topic).add(key);
038  }
039
040  @JsonIgnore
041  public boolean isEmpty() {
042    return toc.isEmpty();
043  }
044
045  /**
046   * @return list of all languages available for this ToC
047   */
048  @JsonIgnore
049  public List<Language> listLanguages() {
050    return Lists.newArrayList(toc.keySet());
051  }
052
053  /**
054   * @return map of all topics for a given language with a list of entry keys for each language
055   */
056  @JsonIgnore
057  public Map<String, List<Integer>> listTopicEntries(Language lang) {
058    if (toc.containsKey(lang)) {
059      return toc.get(lang);
060    }
061    return Maps.newHashMap();
062  }
063
064  public Map<Language, Map<String, List<Integer>>> getToc() {
065    return toc;
066  }
067
068  @Override
069  public boolean equals(Object object) {
070    if (this == object) {
071      return true;
072    }
073    if (!(object instanceof TableOfContents)) {
074      return false;
075    }
076
077    TableOfContents that = (TableOfContents) object;
078    return Objects.equal(this.toc, that.toc);
079  }
080
081  @Override
082  public int hashCode() {
083    return Objects.hashCode(toc);
084  }
085
086  @Override
087  public String toString() {
088    return Objects.toStringHelper(this)
089      .add("toc", toc)
090      .toString();
091  }
092}