const CGI = api.cgi
const F = CGI.getFossilInstance()
const out = api.io.output

const util = import(Fossil.file.dirPart(__FILE)+'reports-util.fossi1ish')
assert 'object' === typename util


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

const sql = api.Buffer(200)
$sql.append <<<EOSQL
        SELECT
            /*0*/uuid AS uuid,
            /*1*/datetime(ev.mtime) AS timestampString,
            /*2*/coalesce(euser, user) AS user,
            /*3*/ev.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,
            /*6*/bgcolor AS bgColor,
            /*7*/mtime AS mtime
            FROM v_reports ev JOIN blob
            WHERE blob.rid=ev.objid
        EOSQL

var yearMonth, yearWeek

if(yearWeek = CGI.getVar('yearWeek')){
    if(Fossil.globMatches({[12][0-9][0-9][0-9]-[0-5][0-9]}, yearWeek)){
        util.year = yearWeek.substr(0,4)
        util.yearWeek = yearWeek.substr(5)
        $sql.append ' ' {
            AND substr(timeStampString,1,4)=%1$Q
            AND strftime('%%W',mtime)=%2$Q
        }.applyFormat(util.year, util.yearWeek)
    }else{
        yearMonth = false
    }
}else if(yearMonth = CGI.getVar('yearMonth')){
    if(Fossil.globMatches({[12][0-9][0-9][0-9]-[0-1][0-9]}, yearMonth)){
        $sql.append ' ' {AND substr(timeStampString,1,7)=%1$Q}.applyFormat(yearMonth)
        util.year = yearMonth.substr(0,4)
    }else{
        yearMonth = false
    }
}else if(util.year){
    $sql.append ' ' {AND substr(timeStampString,1,4)=%1$Q}.applyFormat(util.year)
}
$sql.append ' ' {ORDER BY ev.mtime DESC}

util.initReportsView2(object{
    showFilterLimit:true
})


$out {<h2>}
if(yearMonth || util.year){
    $out {Repository}
}else{
    $out {Recent repository}
}
$out ' activity (' util.getEventTypeLabel() ')'
if(yearWeek){
    $out ' by year/week ' yearWeek
}else if(yearMonth){
    $out ' by year/month ' yearMonth
}else if(util.year){
    $out ' for year ' util.year
}
util.user && $out ' for user ' util.user
$out {</h2>}

util.generateRemoveUserLink()

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


$out {<div>Showing the} ' ' resultLimit ' ' {most recent results.</div>}

const stats = object{
    rowCount: F.selectVal("SELECT COUNT(*) FROM v_reports"),
    shownCount: 0,
    counts: object{
        ci: 0, g: 0, t: 0, w: 0, e: 0
    }    
}
const rowCallback = 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)
    //(stats.shownCount === resultLimit) && return
    stats.counts.(this.3) += 1
    stats.shownCount = rowNumber
    const ce = argv.callee
    const labels = ce.labels || (ce.labels = object{
            ci: 'checkin', g: 'tag', t: 'ticket',
            w: 'wiki', e: 'event'
        })
    const linkRoot = CGI.cgiRoot + 'manifest/'
    const uuidLink = ce.uuidLink || (ce.uuidLink = proc(uuid){
        return {<a href='%1$s?version=%2$s'>%3$.12s</a>}.
            applyFormat(linkRoot, uuid, uuid)
    }.importSymbols('linkRoot'))

    
    const linkParams = object{
        type: util.eventType,
        user: this.2,
        year: util.year ? this.1.substr(0,4) : undefined
    }
    

    const typeLabel = proc(x){
        return {<span class='timeline-entry-type'>}.concat(x, {</span>})
    }

    const bgColor = this.6
    if(bgColor){
        $out {<div class='timeline-entry' style='background-color:} bgColor {'>}
    }else{
        $out {<div class='timeline-entry'>}
    }
    out({<div class='timeline-entry-details'>})
    $out {<span class='timestamp'>%1$s</span>}.applyFormat(this.1)
    $out ' ' {[<span class='uuid'>} uuidLink(this.0) {</span>]}

    $out ' ' typeLabel(labels.(this.3))
    if(!util.user){
        $out ' ' {by [} util.createAnchor('reports/by-week', this.2, linkParams) {]}
    }
    this.4 && $out " in branch [%1$s]".applyFormat(this.4)
    $out {</div>}
    if(this.5/*comment*/){
        out("<div class='timeline-checkin-comment'>",CGI.htmlEscape(this.5),"</div>")
    }
    $out {</div><!-- .timeline-entry -->}
    return rowNumber!==resultLimit
}.importSymbols('out', 'resultLimit', 'CGI', 'util', 'stats')/*just a minor optimization*/

if(stats.rowCount){
    F.db.repo.each(object{
        // optional: mode:0, // collects rows as Objects instead of arrays.
        sql: sql,
        callback: rowCallback
    })
}

Fossil.sorter(stats,true)
$out {<div>}
if(!stats.rowCount){
    assert !stats.shownCount
    $out {No results match the provided filter(s).
        <a href='?'>Try again with no filters</a>?
    }
}else if(stats.shownCount === stats.rowCount){
    $out "All " stats.shownCount " results shown."
}else{
    $out stats.shownCount " results shown of " stats.rowCount " matching the current filter(s)."
    
}
$out {</div>}
if(stats.shownCount < stats.rowCount){
    util.generateLimitLinks()
}

//$out 'Stats: ' stats
