var fs      = require('fs')
var express = require('express')
var router  = express.Router()
var path    = require('path')
var debug   = require('debug')('app:' + path.basename(__filename).replace('.js', ''))
var async   = require('async')
var op      = require('object-path')
var mapper  = require('../helpers/mapper')
var helper  = require('../helpers/helper')

// var program_upcoming = []

router
    .get('/', function(req, res, next) {
        var year = new Date().getUTCFullYear()
        var month = new Date().getUTCMonth() + 1
        debug('Assuming ' + year + '/' + month )
        renderProgram(res, year, month, undefined)
        res.end()
    })
    .get('/:year/:month/:categories*?', function(req, res, next) {
        // debug('Requested "' + req.url + '"' + JSON.stringify(req.params, null, 2))
        renderProgram(res, req.params.year, req.params.month, req.params.categories)
    })

var renderProgram = function renderProgram(res, year, month, categories) {
    debug('Loading "' + path.basename(__filename).replace('.js', '') + '"')
    var all_categories = SDC.get(['local_entities', 'by_class', 'category'], {})
    if (!categories) {
        categories = Object.keys(all_categories).map( function(key) { return parseInt(key) })
    } else {
        categories = categories.split(',').map(function(eid){return parseInt(eid)})
    }
    categories.sort(function(a,b){return a-b})

    program_a = {}
    async.each(SDC.get(['local_entities', 'by_class', 'program']), function(entity, callback) {
        var event = mapper.event(entity.id)
        // debug(JSON.stringify(event, null, 2))
        if (event['start-time']) {

            var pr_categories = op.get(event, ['performance', 'category'], []).map(function(category) { return category.id })
            pr_categories.sort(function(a,b){return a-b})
            // debug(event.id, categories, '?==', JSON.stringify(pr_categories))

            var intersects = false
            var ai = 0, bi = 0
            while( ai < pr_categories.length && bi < categories.length && !intersects )
            {
                if      (pr_categories[ai] < categories[bi]) { ai++ }
                else if (pr_categories[ai] > categories[bi]) { bi++ }
                else { intersects = true }
            }

            if (intersects) {
                // debug(event.id, categories, ' intersects ', JSON.stringify(pr_categories))
            } else {
                // debug(event.id, categories, ' doesnot intersect ', JSON.stringify(pr_categories))
                return
            }

            if (month - 1 !== new Date(event['start-time']).getUTCMonth()) {
                // debug(month - 1, '!==', new Date(event['start-time']).getUTCMonth())
                return
            }
            if (parseInt(year) != new Date(event['start-time']).getUTCFullYear()) {
                // debug(year, '!==', new Date(event['start-time']).getUTCFullYear())
                return
            }

            var event_date = (event['start-time']).slice(0,10)
            var event_time = (event['start-time']).slice(11,16)
            op.set(event, 'event-date', event_date)
            op.set(event, 'event-time', event_time)
            op.push(program_a, [event_date, event_time], event)
        }
        callback()
    }, function(err) {
        if (err) {
            debug('Failed to prepare program.', err)
            callback(err)
            return
        }
        res.render('program', {
            "monthNav": helper.monthNav(year, month),
            "categories": categories,
            "all_categories": all_categories,
            "program": program_a,
            "arraySubtract": helper.arraySubtract,
        })
        res.end()
    })
}


module.exports = router

@@ -360,38 +360,8 @@
 ')%0A%0A
-// var program_upcoming = %5B%5D%0A%0A
 rout
@@ -508,20 +508,29 @@
         
-debu
+// console.lo
 g('Assum
@@ -712,20 +712,26 @@
      // 
-debu
+console.lo
 g('Reque
@@ -965,20 +965,29 @@
 ) %7B%0A    
-debu
+// console.lo
 g('Loadi
@@ -1565,20 +1565,26 @@
      // 
-debu
+console.lo
 g(JSON.s
@@ -1836,36 +1836,42 @@
 %0A            // 
-debu
+console.lo
 g(event.id, cate
@@ -2324,36 +2324,42 @@
              // 
-debu
+console.lo
 g(event.id, cate
@@ -2453,20 +2453,26 @@
      // 
-debu
+console.lo
 g(event.
@@ -2555,32 +2555,43 @@
           return
+ callback()
 %0A            %7D%0A%0A
@@ -2686,20 +2686,26 @@
      // 
-debu
+console.lo
 g(month 
@@ -2775,32 +2775,43 @@
           return
+ callback()
 %0A            %7D%0A 
@@ -2912,20 +2912,26 @@
      // 
-debu
+console.lo
 g(year, 
@@ -2999,32 +2999,43 @@
           return
+ callback()
 %0A            %7D%0A%0A
@@ -3412,20 +3412,26 @@
         
-debu
+console.lo
 g('Faile
@@ -3439,15 +3439,14 @@
  to 
-p
 re
-pare
+nder
  pro

put back lost callbacks