package org.atlasapi.content;

import java.util.concurrent.TimeUnit;

import com.google.common.collect.ImmutableMap;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.joda.time.DateTime;

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 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, ImmutableMap.of(
                        "firstBroadcastBoost", firstBroadcastBoost,
                        "timeBoost", timeBoost,
                        "oneWeek", TimeUnit.MILLISECONDS.convert(7, TimeUnit.DAYS)
                )));
    }
}

@@ -581,545 +581,75 @@
  = %22
-%22%0A            + %22if (_source.broadcasts != null) %7B%22%0A            + %22  now = time();%22%0A            + %22  t = Long.MAX_VALUE;%22%0A            + %22  f = 1;%22%0A            + %22  foreach (b : _source.broadcasts) %7B%22%0A            + %22    candidate = abs(now - b.transmissionTimeInMillis);%22%0A            + %22    if (candidate %3C t) t = candidate;%22%0A            + %22    if (b.repeat = false) f = firstBroadcastBoost;%22%0A            + %22  %7D%22%0A            + %22  _score + (_score * f * timeBoost * (1 / (1 + (t / (t %3C oneWeek ? 50 : 1)))));%22%0A            + %22%7D else _score;
+score_script%22;%0A    public static final String SCRIPT_LANG = %22groovy
 %22;%0A%0A
@@ -1095,16 +1095,16 @@
 30)))))%0A
-
         
@@ -1160,16 +1160,29 @@
 (SCRIPT,
+ SCRIPT_LANG,
  Immutab

Provide script language