package org.ambraproject.wombat.freemarker;

import freemarker.core.Environment;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModelException;
import org.ambraproject.wombat.config.theme.Theme;
import org.ambraproject.wombat.controller.SiteResolver;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.Map;

/**
 * Reads a theme config value into a FreeMarker variable. The param {@code "map"} is the name of the theme config map to
 * read, and the param {@code "value"} is the key of the value to read from the map.
 * <p/>
 * Example invocation:
 * <pre>
 *   <@themeConfig map="widget" value="widgetCount" ; c>
 *     You have ${c}
 *     <#if c == 1>widget<#else>widgets</#if>
 *   </@themeConfig>
 * </pre>
 * This would read the {@code widget.yaml} (or {@code widget.json}) from the current page's theme, extract the {@code
 * "widgetCount"} value from that map, and set that value as {@code c} for the interior of the body.
 */
public class ThemeConfigDirective extends VariableLookupDirective<Object> {

  @Autowired
  private SiteResolver siteResolver;

  @Override
  protected Object getValue(Environment env, Map params) throws TemplateException, IOException {
    Object mapNameObj = params.get("map");
    if (mapNameObj == null) throw new TemplateModelException("map param required");

    Object valueNameObj = params.get("value");
    if (valueNameObj == null) throw new TemplateModelException("value param required");

    Theme theme = new SitePageContext(siteResolver, env).getSite().getTheme();
    Map<String, Object> configMap = theme.getConfigMap(mapNameObj.toString());
    if (configMap == null) {
      throw new TemplateModelException("No config map exists for: " + mapNameObj);
    }

    return configMap.get(valueNameObj.toString());
  }

}

@@ -167,24 +167,76 @@
 lException;%0A
+import org.ambraproject.wombat.config.site.SiteSet;%0A
 import org.a
@@ -274,16 +274,16 @@
 .Theme;%0A
-
 import o
@@ -1069,16 +1069,203 @@
 e body.%0A
+ * %3Cp/%3E%0A * The optional %7B@code %22journal%22%7D param will look up the theme for another site, based on the site's configured journal%0A * key, and return a config value from that theme instead.%0A
  */%0Apubl
@@ -1337,16 +1337,56 @@
 ect%3E %7B%0A%0A
+  @Autowired%0A  private SiteSet siteSet;%0A
   @Autow
@@ -1797,24 +1797,75 @@
 equired%22);%0A%0A
+    Object journalKeyObj = params.get(%22journal%22);%0A%0A
     Theme th
@@ -1931,16 +1931,147 @@
 heme();%0A
+    if (journalKeyObj != null) %7B%0A      theme = theme.resolveForeignJournalKey(siteSet, journalKeyObj.toString()).getTheme();%0A    %7D%0A
     Map%3C

Extend ThemeConfigDirective to look up values from other sites