class TendersAwardsYears extends GenericOCDSController {

    @ApiOperation(value = "Computes all available years from awards.date, tender.tenderPeriod.startDate")
    @RequestMapping(value = "/api/tendersAwardsYears", method = {RequestMethod.POST,
            RequestMethod.GET}, produces = "application/json")
    public List<Document> tendersAwardsYears() {

        BasicDBObject project1 = new BasicDBObject();

        project1.put(
                "tenderYear",
                new BasicDBObject(
                        "$cond",
                        Arrays.asList(
                                new BasicDBObject(
                                        "$gt",
                                        Arrays.asList(ref(MongoConstants.FieldNames.TENDER_PERIOD_START_DATE), null)
                                ),
                                new BasicDBObject("$year", ref(MongoConstants.FieldNames.TENDER_PERIOD_START_DATE)),
                                null
                        )
                )
        );

        project1.put(
                "awardYear",
                new BasicDBObject("$cond", Arrays.asList(
                        new BasicDBObject("$gt", Arrays.asList(ref(MongoConstants.FieldNames.AWARDS_DATE), null)),
                        new BasicDBObject("$year", ref(MongoConstants.FieldNames.AWARDS_DATE)), null
                ))
        );
        project1.put(Fields.UNDERSCORE_ID, 0);

        BasicDBObject project2 = new BasicDBObject();
        project2.put("year", Arrays.asList("$tenderYear", "$awardYear"));

        Aggregation agg = Aggregation.newAggregation(
                project().and(MongoConstants.FieldNames.TENDER_PERIOD_START_DATE)
                        .as(MongoConstants.FieldNames.TENDER_PERIOD_START_DATE)
                        .and(MongoConstants.FieldNames.AWARDS_DATE)
                        .as(MongoConstants.FieldNames.AWARDS_DATE),
                match(new Criteria().orOperator(
                        where(MongoConstants.FieldNames.TENDER_PERIOD_START_DATE).exists(true),
                        where(MongoConstants.FieldNames.AWARDS_DATE).exists(true)
                )),
                new CustomUnwindOperation("$awards", true), new CustomProjectionOperation(project1),
                new CustomProjectionOperation(project2), new CustomUnwindOperation("$year"),
                match(where("year").ne(null)),
                new CustomGroupingOperation(new BasicDBObject(Fields.UNDERSCORE_ID, "$year")),
                new CustomSortingOperation(new BasicDBObject(Fields.UNDERSCORE_ID, 1))
        );

        return releaseAgg(agg);
    }

}