def findBodyText()

in src/main/scala/com/gu/octopusthrift/services/ArticleFinder.scala [61:89]


  def findBodyText(bundle: OctopusBundle): Option[OctopusArticle] = {

    // Given a bundles worth of articles, pick only the ones that are Body Text, Panel Text or Tabular Text
    val onlyBodyTextArticles: Array[OctopusArticle] =
      bundle.articles
        .map(a => a.copy(object_type = cleanObjectType(a.object_type)))
        .filter(a =>
          bodyTextObjects.contains(a.object_type) && validPublicationDestinations
            .contains(a.for_publication.toLowerCase()))

    if (onlyBodyTextArticles.isEmpty)
      // There are no suitable articles
      None
    else if (onlyBodyTextArticles.length == 1)
      // There's only one suitable article
      onlyBodyTextArticles.headOption
    else {
      // Given a number of suitable articles, group them by their publication destination
      val groupedByDestination: Map[String, Array[OctopusArticle]] =
        onlyBodyTextArticles.groupBy(_.for_publication.toLowerCase)

      // Pick the available articles for the destination we prefer the most, then group them by object type
      val forPreferredDestinationAndGroupedByType: Map[String, Array[OctopusArticle]] =
        articlesForPreferredDestination(groupedByDestination).groupBy(_.object_type)

      // Pick the article with the most preferred object type and the lowest object number
      articlesOfPreferredObjectType(forPreferredDestinationAndGroupedByType).sorted.headOption
    }
  }