const CGI = api.cgi
const F = Fossil.cx
const out = api.io.output

CGI.setContentType('text/plain')

out("Timeline of recent repository events for project ", F.getProjectName(),"...\n\n")

const defaultLimit = 10
var resultLimit = +CGI.getVar('limit', defaultLimit)
if(resultLimit<=0){
  out("The 'limit' value is too small. Using the default.\n\n")
  resultLimit = defaultLimit
}else if(resultLimit>100){
  out("The 'limit' value is too large. Using the default.\n\n")
  resultLimit = defaultLimit
}

0 && scope {
    // arguable but potentially useful later on
    CGI.setCookie('limit', resultLimit)
}

out("The ",resultLimit," most recent timeline entries, ",
    "as of ",strftime("%Y-%m-%d %H:%M:%S"),
    " (server time)...\n\n")

F.db.repo.each(object{
    mode:1/*0==object, else array. Yes, it's a silly heuristic.*/,
    sql: <<<EOSQL
        SELECT
            /*0*/uuid AS uuid,
            /*1*/datetime(event.mtime) AS timestampString,
            /*2*/coalesce(euser, user) AS user,
            /*3*/event.type AS eventType,
            /*4*/(SELECT group_concat(substr(tagname,5), ',') FROM tag, tagxref
                  WHERE tagname GLOB 'sym-*' AND tag.tagid=tagxref.tagid
                  AND tagxref.rid=blob.rid AND tagxref.tagtype>0)
                  AS tags,
            /*5*/coalesce(ecomment, comment) AS comment
            FROM event JOIN blob
            WHERE blob.rid=event.objid
            ORDER BY event.mtime DESC
        EOSQL,
    callback: proc(){
        // 'this' is the row's Object or Array, as determined by 'mode'.
        // The callback mechanism sets up the local variables rowNumber
        // (1-based number of rows traversed) and columnNames (array of
        // strings).
        //print(this.join(' | '))
        //print(rowNumber,columnNames)
        const labels = argv.callee.labels || (argv.callee.labels = object{
                ci: 'checkin', g: 'tag', t: 'ticket',
                w: 'wiki', e: 'event'
            })
        out("%1$s @ %2$s [%3$.12s] by [%4$s]".
                  applyFormat( labels.(this.3), this.1, this.0, this.2) )
        this.4 && out(" in branch [%1$s]".applyFormat(this.4))
        out("\n\t",this.5,"\n\n")
        return rowNumber!==resultLimit
    }.importSymbols('out'/*just a minor optimization*/)
})

if(+CGI.getVar('showSrc',false)){
    out("The entire contents of this script file follow:\n",
        {========================================================================},
        "\n")

    out(slurpFile(__FILE))
}
