//graph schema is on page 13 https://ldbc.github.io/ldbc_snb_docs/ldbc-snb-specification.pdf
//BI 1 query description is on page 59 https://ldbc.github.io/ldbc_snb_docs/ldbc-snb-specification.pdf

SET syntax_version = "v2"
USE GRAPH ldbc_snb
DROP QUERY bi_1

CREATE QUERY bi_1(DATETIME maxDate) FOR GRAPH ldbc_snb {
  TYPEDEF TUPLE <INT theYear, BOOL isComment, STRING lengthCategory, INT messageCount, INT averageMessageLength, INT sumMessageLength, FLOAT percentageOfMessages> MessageInfo;

  HeapAccum<MessageInfo>(1, theYear DESC, isComment ASC, lengthCategory ASC) @@result;
  OrAccum @isComment;
  SumAccum<STRING> @lengthCategory;
  GroupByAccum<INT theYear, BOOL isComment, STRING lengthCategory, SumAccum<INT> messageCount, SumAccum<INT> sumMessageLength> @@calc;

  INT total;

  vStart = { Post.*, Comment.* };
  vStart = 
    SELECT s
    FROM vStart:s
    WHERE s.creationDate < maxDate
    ACCUM 
      s.@isComment = (s.type == "Comment"),
      IF s.length < 40 THEN
        s.@lengthCategory = "0"
      ELSE IF s.length < 80 THEN
        s.@lengthCategory = "1"
      ELSE IF s.length < 160 THEN
        s.@lengthCategory = "2"
      ELSE
        s.@lengthCategory = "3"
      END
    POST-ACCUM @@calc += (year(s.creationDate), s.@isComment, s.@lengthCategory -> 1, s.length);

  total = vStart.size();
  @@result.resize(total);
  FOREACH c IN @@calc DO
    @@result += MessageInfo(c.theYear, c.isComment, c.lengthCategory, c.messageCount, (c.sumMessageLength / c.messageCount), c.sumMessageLength, (c.messageCount * 1.0 / total));
  END;

  PRINT @@result;
}

// INSTALL QUERY bi_1
// RUN QUERY bi_1("2011-07-22 00:00:00")
SET query_timeout = 180000
INTERPRET QUERY bi_1("2011-07-22 00:00:00")
