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(__FILE) || return

const fUser = util.user

$out {<h2>Repository activity (} util.getEventTypeLabel() {) by year/month}
fUser && $out ' for user ' fUser
$out {</h2>}
util.generateRemoveUserLink()


var stmt = F.db.prepare({
        SELECT substr(date(mtime),1,7) AS timeframe,
        count(*) AS eventCount
        FROM v_reports
        GROUP BY timeframe ORDER BY timeframe DESC})


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

stmt.reset()

var nEventTotal = 0, rowNumber = 0
if(!maxEvents){
    $out {<div>No activity for this time period</div>}
}else{
    $out <<<EOF
        <table class='reports-table-events' border='0' cellpadding='2' cellspacing='0'>
        <thead><tr>
        <th>Year/Month</th>
        <th>Events</th>
        <th width='90%'><!-- relative commits graph --></th>
        </tr></thead><tbody>
    EOF
    const timeLink = proc(time){
        return util.createAnchor( 'timeline', time, object{
                yearMonth: time,
                year: undefined
        })
    }
    var user, nSize, timeframe, showYearTotal = 0, prevYear, year
    var nEventsPerYear = 0
    while(stmt.step()){
        rowNumber += 1
        timeframe = stmt.get(0)
        nCount = stmt.get(1)
        nCount || continue
        nSize = nCount ? (100 * nCount / maxEvents) : 0
        nSize || (nSize=1)
        showYearTotal = 0
        year = timeframe.substr(0,4)
        if(!prevYear || (prevYear !== year)){
            showYearTotal = prevYear;
            if(showYearTotal){
                $out {<tr><td>Yearly total</td><td colspan='2'>} nEventsPerYear {</td></tr>}
            }
            nEventsPerYear = 0
            prevYear = year
            $out {<tr><th colspan='3' class='reports-row-year'>} prevYear {</th></tr>}
        }

        nEventTotal += nCount
        nEventsPerYear += nCount
        
        $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>}
    }

    if(!showYearTotal && prevYear){
        /* Add final year total separator */
        $out {<tr><td>Yearly total</td><td colspan='2'>} nEventsPerYear {</td></tr>}
    }
    $out <<<EOF
        </tbody></table>
    EOF
}
stmt.finalize()

if(!util.year && nEventTotal){
    const nAvg = rowNumber ? (nEventTotal/rowNumber) : 0
    $out {<br/><div>Total events:} ' ' nEventTotal {<br/>}
    $out {Average per active month:} ' ' nAvg {</div>}
}
