package org.atlasapi.content;

import java.util.concurrent.TimeUnit;

import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.joda.time.DateTime;

import com.google.common.collect.ImmutableMap;

public class BroadcastQueryBuilder {

    public static final String SCRIPT = ""
            + "if (_source.broadcasts != null) {"
            + "  now = time();"
            + "  t = Long.MAX_VALUE;"
            + "  f = 1;"
            + "  foreach (b : _source.broadcasts) {"
            + "    candidate = abs(now - b.transmissionTimeInMillis);"
            + "    if (candidate < t) t = candidate;"
            + "    if (b.repeat = false) f = firstBroadcastBoost;"
            + "  }"
            + "  _score + (_score * f * timeBoost * (1 / (1 + (t / (t < oneWeek ? 50 : 1)))));"
            + "} else _score;";
    public static final String SCRIPT_LANG = "groovy";

    public static QueryBuilder build(QueryBuilder childQuery, Float timeBoost,
            Float firstBroadcastBoost) {
        return QueryBuilders.functionScoreQuery(
                QueryBuilders.filteredQuery(childQuery,
                        FilterBuilders.nestedFilter(EsContent.BROADCASTS,
                                FilterBuilders.rangeFilter(EsBroadcast.TRANSMISSION_TIME)
                                        .from(new DateTime().minusDays(30))
                                        .to(new DateTime().plusDays(30)))))
                .add(ScoreFunctionBuilders.scriptFunction(SCRIPT, SCRIPT_LANG, ImmutableMap.of(
                        "firstBroadcastBoost", firstBroadcastBoost,
                        "timeBoost", timeBoost,
                        "oneWeek", TimeUnit.MILLISECONDS.convert(7, TimeUnit.DAYS)
                )));
    }
}

@@ -524,19 +524,42 @@
 + %22 
+var
  now = 
-time
+DateTime.now().getMillis
 ();%22
@@ -576,16 +576,20 @@
    + %22  
+var 
 t = Long
@@ -618,16 +618,20 @@
    + %22  
+var 
 f = 1;%22%0A
@@ -654,16 +654,17 @@
  for
+ 
 each (b 
 : _s
@@ -659,17 +659,18 @@
 each (b 
-:
+in
  _source
@@ -704,16 +704,20 @@
  + %22    
+var 
 candidat
@@ -720,16 +720,21 @@
 idate = 
+Math.
 abs(now 
@@ -852,16 +852,17 @@
 repeat =
+=
  false) 
@@ -1085,14 +1085,18 @@
  = %22
-groovy
+javascript
 %22;%0A%0A

Change to JS