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


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

const currentYear = strftime('%Y')

var sqlBuf = api.Buffer(200)
sqlBuf.append({
    SELECT DISTINCT strftime('%Y-%W',mtime) AS wkyear,
    count(*) AS n
    FROM v_reports
    WHERE mtime < current_timestamp})
if(util.year){
    sqlBuf.append(' ',{AND substr(date(mtime),1,4)=})
    sqlBuf.appendf(" %1$Q", util.year || currentYear)
}
sqlBuf.append(' ', {GROUP BY wkyear ORDER BY wkyear DESC})
//$out sqlBuf.toString() '\n'

$out {<h2>}
if(util.year){
    $out {Repository activity (} util.getEventTypeLabel() {) for the calendar weeks of} ' ' util.year
}else{
    $out {Repository activity (} util.getEventTypeLabel() {) by calendar week for all years}
}
util.user && $out ' for user ' util.user
$out {</h2>}

util.generateRemoveUserLink(object{year:util.year})

const stmt = F.db.prepare(sqlBuf)

var maxEvents = 0, nCount, rowCount = 0
while(stmt.step()){
    nCount = stmt.get(1)
    rowCount += 1
    (nCount>maxEvents) && (maxEvents = nCount)
}
stmt.reset()

var nEventTotal = 0, rowNumber = 0
if(!maxEvents){
    $out {<div>No results for year} ' ' util.year ' ' {using the current filter(s).</div>}
}else{
    $out <<<EOF
        <table class='reports-table-events' border='0' cellpadding='2' cellspacing='0'>
        <thead><tr>
        <th>Week</th>
        <th>Events</th>
        <th width='90%'><!-- relative commits graph --></th>
        </tr></thead><tbody>
    EOF
    const timeLink = proc(time){
        //return time
        //util.year || return time
        return util.createAnchor( 'timeline', time.substr(5,2), object{
                yearWeek: time,
                year: undefined
        })
    }
    var nSize, timeframe, showYearTotal = 0
    var prevYear, yearPart
    while(stmt.step()){
        nCount = stmt.get(1)
        nCount || continue
        nEventTotal += nCount
        rowNumber += 1
        timeframe = stmt.get(0)
        nSize = nCount ? (100 * nCount / maxEvents) : 0
        nSize || (nSize=1)
        yearPart = timeframe.substr(0,4)

        if(prevYear !== yearPart){
            prevYear = yearPart
            $out {<tr><th colspan='3'>} yearPart {</th></tr>}
        }
        
        $out {<tr>}
        //$out {<tr class=} ((rowNumber%2) ? {'odd'} : {'even'}) {>}
        $out {<td>} [timeLink timeframe] {</td>}
        $out {<td>} nCount {</td>}
        $out {<td><div class='reports-graph-line' style=}
        $out {'width:%1$d%%;'}.applyFormat(nSize) {>&nbsp;</div>}
        $out {</td></tr>}
    }
    $out {</tbody></table>}
}
stmt.finalize()

if(nEventTotal){
    const nAvg = rowNumber ? (nEventTotal/rowNumber) : 0
    $out {<br/><div>Total events:} ' ' nEventTotal {<br/>}
    $out 'Average per active week: ' nAvg {</div>}
}
