%dw 2.0
input in0 application/csv streaming=true

fun collectUnitDifferentPid( p: Array<{ ID: String, PARENT_ID: String }>, pid: String, index: Number, record: { ID: String, PARENT_ID: String }) = do {
    var myVar = p[index]
    ---
    if (myVar.PARENT_ID == pid)
        collectUnitDifferentPid(p , pid, index + 1, myVar)
    else
        {record: record, index: index}
}
fun group(p: Array<{ ID: String, PARENT_ID: String }>, index: Number = 0) =
  if (!p[index]?)
    []
  else do {
    var startRecord = p[index]
    var endRecord = collectUnitDifferentPid(p, startRecord.PARENT_ID, index, startRecord)
    ---
    [{ID: startRecord.PARENT_ID, recordStart: startRecord.ID, recordEnd: endRecord.record.ID} ~ group(p, endRecord.index)]
  }
output application/json
---
group(in0)