/*
 * Index page.
 */

'use strict'

var fs       = require('fs')
  , path     = require('path')
  , readline = require('readline')
  , async    = require('async')
  , router   = require('express').Router()

var util   = require('../lib/util')
  , parse    = require('../lib/parse')
  , ts       = require('../lib/timestamp')
  , sort     = require('../lib/sort')

var defaultSortingKeys = ['subarch', 'os', 'cc', 'comment', 'slot']
  , defaultSortingFn   = sort.byKeys(defaultSortingKeys)

function checkQuery (check, src) {
  if (!src) return false
  var keys = Object.keys(check)
  for (var i = 0; i < keys.length; i++) {
    var key = keys[i]
    if (check[key] !== src[key]) return false
  }
  return true
}

function handleIndex (req, res, next) {
  res.set('Cache-Control', 'public, max-age=60') // one minute
  // Always contain the short branch name (e.g. v2.4).
  var branch = res.locals.branch = req.params.branch || 'master'
  // TODO
  var check = checkQuery.bind(null, {
    branch: branch
  })

  fs.readdir(util.dir, function handleSlots (err, slots) {
    if (err) {
      err.message = 'util.dir not found. Did you set up config.js'
                  + 'correctly?'
      err.message = 'FATE data not found.'
      err.status = 404
      return next(err)
    }

    fs.readFile(path.join(util.dir, 'branches'), 'utf8',
                function (err, data) {
      if (err) {
        res.locals.branches = ['master']
      } else {
        // readline? nah.
        var branches = data
                         .split('\n')
                         .filter(function (b) { return b })
                         .sort()
                         .reverse()
        branches.unshift('master')
        res.locals.branches = branches
      }
      
      if (res.locals.branches.indexOf(branch) === -1) {
        err = new Error('Branch not found')
        err.status = 404
        return next(err)
      }

      // For every slot get the summary of the latest results.
      async.map(slots, function iterator (slot, out) {
        var slotdir = path.join(util.dir, slot)

        // If the slot is marked as hidden then skip over it.
        // All the null members of the array will be cleaned at
        // the end().
        fs.exists(path.join(slotdir, 'hidden'), function (exists) {
          if (exists) return out(null, null)
          // Load summary
          parse.loadSummary(slot, 'latest',
                            function summaryCb (err, summary) {
            // Ignore possible errors in one specific report in order
            // not to destroy the entire history page.
            if (err || !check(summary)) return out(null, null)
            
            parse.loadSummary(slot, 'previous', function prevCb (err, prev) {
              if (err || !prev) return out(null, [ summary ])
              out(null, [ summary, prev ])
            })
          })
        })
      }, function end (err, reps) {
        // The server side sorting is only for default sorting.
        // Client-side sorting through FooTable handles
        // everything else.
        // XXX: should we implement CGI-style server-side sorting too?
        res.locals.reps =
          reps
            .filter(function (n) {
              // Filter out null/invalid ones
              // Also hack to make broken results invisible
              return n != null && n[0].os
            })
            .sort(function (a, b) {
              return defaultSortingFn(a[0], b[0]) 
            })
        res.render('index.ejs')
      })
    })
  })
}

router.get('/', handleIndex)
router.get('/index.cgi', handleIndex)
router.get('/:branch', handleIndex)

module.exports = router

@@ -838,14 +838,8 @@
 the 
-short 
 bran
@@ -850,20 +850,17 @@
 ame 
-(e.g. v
+like n
 2.4
-).
 %0A  v
@@ -932,16 +932,19 @@
 / TODO%0A 
+ //
  var che
@@ -973,16 +973,19 @@
 ull, %7B%0A 
+ //
    branc
@@ -995,16 +995,19 @@
 branch%0A 
+ //
  %7D)%0A%0A  f
@@ -1907,24 +1907,663 @@
 r)%0A      %7D%0A%0A
+      var match = branch.match(/%5Ev(%5B0-9%5D%5C.%5B0-9%5D)$/)%0A      var re%0A      if (match) %7B%0A        // If the branch is a release branch, filter slot names%0A        re = RegExp('-n' + match%5B1%5D + '$')%0A        slots = slots.filter(function (s) %7B return re.test(s) %7D)%0A      %7D else if (branch === 'master') %7B%0A        // If not, filter out all release branches%0A        re = /-n%5B0-9%5D%5C.%5B0-9%5D$/%0A        slots = slots.filter(function (s) %7B return !re.test(s) %7D)%0A      %7D else %7B%0A        // If it is not a branch at all%0A        err = new Error('Need to update branch list. Please file a bug report.')%0A        err.status = 500%0A        return next(err)%0A      %7D%0A%0A
       // For
@@ -3237,16 +3237,16 @@
 y page.%0A
+
         
@@ -3260,27 +3260,8 @@
 (err
- %7C%7C !check(summary)
 ) re

Optimize branch filtering