package tv.pluto.mongo.utils;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.bson.Document;

public class DocumentUtils extends MongoUtils {
  public DocumentUtils(String collection) {
    super(collection, new Document());
  }

  public Document getTimelinesWithStartAfterCurrentDate(int time) {
    List<Document> pipeline =
        Arrays.asList(
            new Document(
                "$lookup",
                new Document()
                    .append("from", "episodes")
                    .append("localField", "episode")
                    .append("foreignField", "_id")
                    .append("as", "episode")),
            new Document("$unwind", "$episode"),
            new Document("$match", new Document("episode.published", true)),
            new Document(
                "$lookup",
                new Document()
                    .append("from", "series")
                    .append("localField", "episode.series")
                    .append("foreignField", "_id")
                    .append("as", "series")),
            new Document(
                "$match",
                new Document()
                    .append("episode.series", new Document("$ne", null))
                    .append("series.0", new Document("$exists", true))),
            new Document(
                "$lookup",
                new Document()
                    .append("from", "channels")
                    .append("localField", "episode.channels")
                    .append("foreignField", "_id")
                    .append("as", "channels")),
            new Document(
                "$match",
                new Document()
                    .append("channels.0", new Document("$exists", true))
                    .append(
                        "start",
                        new Document("$gte", new Date(System.currentTimeMillis() + time)))),
            new Document(
                "$project",
                new Document()
                    .append("_id", 1)
                    .append("start", 1)
                    .append("stop", 1)
                    .append("episode._id", 1)
                    .append("channel", 1)
                    .append("series._id", 1)));

    return (Document) genericCollection.aggregate(pipeline).first();
  }
}
