text:
var express = require('express')
var router = express.Router()
var path = require('path')
var moment = require('moment')
var tog = require('../../../../lib/tog.js')
var request = require('request')
var calendar = require('node-calendar')
var moment = require('moment')
const crypto = require('crypto')

var versionNumber = '8'
var filePath = '../../../../app/views/fha/v' + versionNumber
var viewPath = 'fha/v' + versionNumber

var staffDataHoliday = require(filePath + '/data/staff-data-holiday.js')
var staffData2 = require(filePath + '/data/staff-data-2.js')
var slotsData = require(filePath + '/data/slots-data.js')
var slotsData2 = require(filePath + '/data/slots-data-2.js')
var commentsData = require(filePath + '/data/comments.js')
var appointmentHistory = require(filePath + '/data/appointmentHistory.js')

router.get('*', function (req, res, next) {
  // path is only available with the proper value within this sub-module/router.
  res.locals.path = req.baseUrl.substr(1)
  // create some other useful path variables.
  var bits = req.params[0].substr(1).split('/')
  res.locals.path1 = res.locals.path + '/' + bits[0]
  res.locals.path2 = res.locals.path + '/' + bits[0] + '/' + bits[1]
  res.locals.stage = 1

  res.locals.cssPath = '/public/stylesheets/fha_v' + versionNumber + '.css'
  res.locals.javascriptPath = '/public/javascripts/application_v' + versionNumber + '.js'
  res.locals.versionNumber = versionNumber

  if (!req.session.data.socialWorkComments) {
    req.session.data.socialWorkComments = []
  }

  if (!req.session.data.typicalDayComments) {
    req.session.data.typicalDayComments = []
  }
  if (!req.session.data.observedBehaviourComments) {
    req.session.data.observedBehaviourComments = []
  }

  if (!req.session.data.observations) {
    req.session.data.observations = []
  }

  res.locals.menuItems = require(filePath +'/caselist/_navItems.js')(versionNumber, reviewCustomers, assessmentCustomers, appointmentCustomers );
  res.locals.menuItemsDm = require(filePath +'/caselist/_navItemsDM.js')(versionNumber, dmCustomers );

  next()
})

router.get('/', function (req, res, next) {
  res.locals.reviewNumbers = {
    total: reviewCustomers.length,
    readyForReview: reviewCustomers.filter(customer => customer.status === 'review').length,
    fme: reviewCustomers.filter(customer => customer.status === 'fme').length
  }
  next()
})

router.get('/', function (req, res, next) {
  res.locals.appointmentNumbers = {
    total: appointmentCustomers.length,
    readyToBook: appointmentCustomers.filter(customer => customer.status === 'Ready to book').length,
    booked: appointmentCustomers.filter(customer => customer.status === 'Booked').length,
    didNotAttend: appointmentCustomers.filter(customer => customer.status === 'Did not attend').length
  }
  next()
})

router.get('/', function (req, res, next) {
  res.locals.assessNumbers = {
    total: assessmentCustomers.length,
    readyForAssessment: assessmentCustomers.filter(customer => customer.status === 'Ready for assessment').length,
    assesmentComplete: assessmentCustomers.filter(customer => customer.status === 'Assessment completed').length,
    assesmentStopped: assessmentCustomers.filter(customer => customer.status === 'Assessment stopped').length,
    appointmentToday: assessmentCustomers.filter(customer => customer.status === 'Appointment today').length,
    readyToBook: assessmentCustomers.filter(customer => customer.status === 'Ready to book').length,
    booked: assessmentCustomers.filter(customer => customer.status === 'Booked').length

  }
  next()
})

router.get('/', function (req, res, next) {
  res.locals.dmNumbers = {
    total: dmCustomers.length,
    assessmentReports: dmCustomers.filter(customer => customer.status === 'Assessment reports').length,
    failedToAttend: dmCustomers.filter(customer => customer.status === 'Failed to attend appointment').length,
    questionnaireNotReturned: dmCustomers.filter(customer => customer.status === 'Questionnaire not returned').length

  }
  next()
})

router.post('*', function (req, res, next) {
  // path is only available with the proper value within this sub-module/router.
  res.locals.path = req.baseUrl.substr(1)
  // create some other useful path variables.
  var bits = req.params[0].substr(1).split('/')
  res.locals.path1 = res.locals.path + '/' + bits[0]
  res.locals.path2 = res.locals.path + '/' + bits[0] + '/' + bits[1]
  res.locals.stage = 1

  res.locals.cssPath = '/public/stylesheets/fha_v' + versionNumber + '.css'
  res.locals.javascriptPath = '/public/javascripts/application_v' + versionNumber + '.js'
  res.locals.versionNumber = versionNumber

  if (!req.session.data.socialWorkComments) {
    req.session.data.socialWorkComments = []
  }

  if (!req.session.data.typicalDayComments) {
    req.session.data.typicalDayComments = []
  }

  if (!req.session.data.observedBehaviourComments) {
    req.session.data.observedBehaviourComments = []
  }

  if (!req.session.data.conditionComments) {
    req.session.data.conditionComments = []
  }

  if (!req.session.data.observations) {
    req.session.data.observations = []
  }

  res.locals.menuItems = require(filePath + '/caselist/_navItems.js')(versionNumber, reviewCustomers, assessmentCustomers, appointmentCustomers);
  res.locals.menuItemsDm = require(filePath +'/caselist/_navItemsDM.js')(versionNumber, dmCustomers );

  next()
})

router.get('/miarussell/*', function (req, res, next) {
  res.locals.firstname = 'Mia'
  next()
})

router.get('/victorcastillo/*', function (req, res, next) {
  res.locals.firstname = 'Victor'
  next()
})

router.get('/cookies/', function (req, res, next) {
  res.send(tog(req.cookies))
})

router.get('*/record_phys_exam', function (req, res, next) {
  req.session.data.physexam = true
  // res.send(tog(req.session.data));
  // res.send(tog(req.params[0]));
  res.redirect('/' + res.locals.path + '/victorcastillo/evidence/finish')
})

var nug_id = 0

/*
  Used to save indiviudal "nuggets" of evidence from the add evidence screen
*/
router.post('/saveText/', function (req, res, next) {
  var newNugget = {
    'text': req.body.nugget,
    'id': nug_id++,
    'time': new Date()
  }
  req.session.data.nuggets = req.session.data.nuggets ? req.session.data.nuggets : []
  req.session.data.nuggets.push(newNugget)
  res.send(tog(req.session.data))
})

/*
  Clears session (triggered by little link at bottom of pages)
*/
router.get('/clearSession', function (req, res, next) {
  req.session.data.nuggets = []
  req.session.data.withdesc = false
  req.session.data.physexam = false
  req.session.data = {}
  observations = []
  req.session.data.socialWorkComments = []
  req.session.data.typicalDayComments = []
  req.session.data.observedBehaviourComments = []
  req.session.data.conditionComments = []
  nug_id = 0
  res.send('success')
})

router.post('/updateEvidence', function (req, res, next) {
  var id = req.body.id
  var nug = _.find(req.session.data.nuggets, {'id': parseInt(id)})
  nug.descriptors = req.body.descriptors
  req.session.data.withdesc = true
  res.send(tog(req.session.data.nuggets))
})

router.get('/prefillAssessment', function (req, res, next) {
  req.session.data.nuggets = []
  var bits = [
    'The client experiences nausea as a result of their pain medication',
    "He says he used to sleep a lot but isn't doing that so much anymore",
    'Broke his right leg in Aug 2015 following a motorbike accident. He fractured the whole of his leg. He had surgery and has 2 bolts in his knee to hold his knee together. He also has an external fixator on his right let from his knee down. Had been to physiotherapy twice but has been told there is only so much that they can do until his leg is healed.',
    "Some days he can't to the exercises at all due to pain",
    'They have given him basic leg exercises to do at home to help build his calf muscle. He has a lot of muscle wasting in his right thigh and says the exercises are helping a bit',
    'Has an appointment with the surgeon today and is getting hospital transport there',
    'Is seeign his surgeon regularly for review of his leg and to adjust his fixator, seeing him every couple of weeks and having the fixator adjusted every week',
    "His specialist has advised that it will be about 4 months before he will heal and the cage will be removed. Has had the cage on for 6 weeks now. He says at first he couldn't do anything and was housebound. Now he is able to do more with the use of 2 crutches. Can weight bare a little bit now on his right leg",
    'Used to take morphine for pain but is not taking this anymore as his pain is improving'
  ]
  var time = moment(new Date())
  for (var i = bits.length - 1; i > -1; i--) {
    // console.log(time)
    var newNugget = {
      'text': bits[i],
      'id': i,
      'time': moment(time)
    }
    // console.log(newNugget)
    req.session.data.nuggets.push(newNugget)
    time.subtract(3, 'minutes')
  }
  nug_id = bits.length
  req.session.data.physexam = true
  res.send('success')
})

var arrivedTime = ''

var getAppointmentDates = function () {
  var appointments = {}

  appointments.nextAvailable = moment().add(15, 'days').hours(11).minutes(0)
  appointments.today = moment().hours(14).minutes(0)

  return appointments
}

router.get('*', function (req, res, next) {
  // path is only available with the proper value within this sub-module/router.
  res.locals.path = req.baseUrl.substr(1)
  // create some other useful path variables.
  var bits = req.params[0].substr(1).split('/')
  res.locals.root = '/fha/v' + versionNumber
  res.locals.manageStaffPath = viewPath + '/capacity/manage-staff'
  res.locals.path1 = res.locals.path + '/' + bits[0]
  res.locals.path2 = res.locals.path + '/' + bits[0] + '/' + bits[1]
  res.locals.stage = req.cookies.stage || 1
  res.locals.query = req.query
  res.locals.arrivedTime = arrivedTime

  // res.locals.staff = staffData;
  res.locals.appointments = getAppointmentDates()

  for (property in req.session.data) {
    res.locals[property] = req.session.data[property]
  }

  next()
})

router.post('*', function (req, res, next) {
  // path is only available with the proper value within this sub-module/router.
  res.locals.path = req.baseUrl.substr(1)
  // create some other useful path variables.
  var bits = req.params[0].substr(1).split('/')
  res.locals.root = '/fha/v' + versionNumber
  res.locals.manageStaffPath = viewPath + '/capacity/manage-staff'
  res.locals.path1 = res.locals.path + '/' + bits[0]
  res.locals.path2 = res.locals.path + '/' + bits[0] + '/' + bits[1]
  res.locals.stage = req.cookies.stage || 1
  res.locals.query = req.query
  res.locals.arrivedTime = arrivedTime

  // res.locals.staff = staffData;
  next()
})

router.get('/booking/mendez*', function (req, res, next) {

})
router.post('/booking/cancel-appointment', function (req, res, next) {
  if (req.body.change_now === 'true') {
    res.redirect('timepicker')
  } else {
    res.redirect('/fha/v' + versionNumber + '/appointments-changed?reason=' + req.body.reason)
  }
})

function getCentreDetails (req, res) {
  var centres = require(filePath + '/data/centres.js'),
    centreId = req.params.centreId

  if (centreId) {
    res.locals.centre = centres[centreId]
    res.locals.centre.id = centreId
  } else {
    res.locals.centre = centres['fiveways']
    res.locals.centre.id = 'fiveways'
  }
};

router.get('/assessment-centres', function (req, res, next) {
  res.locals.centres = require(filePath + '/data/centres.js')
  next()
})

router.get('/booking/history', function (req, res, next) {
  res.locals.comments = commentsData
  next()
})

router.post('/booking/history', function (req, res, next) {
  var time = new Date()
  res.locals.comments = commentsData

  res.locals.comments.push({
    comment: req.body.comment,
    timestamp: time.getTime(),
    dateFormatted: moment(time).format('dddd DD MMM YYYY hh:mm a'),
    name: 'Shelia Hopper',
    hasComment: true,
    isCustomer: true
  })
  res.render(viewPath + '/booking/history')
})
router.post('/booking/cancel-appointment', function (req, res, next) {
  if (req.body.change_now === 'true') {
    res.redirect('timepicker')
  } else {
    res.redirect('/fha/v' + versionNumber + '/appointments-changed?reason=' + req.body.reason)
  }
})

router.post('/booking/bobby_timeline', function (req, res, next) {
  var time = new Date()
  commentsData.push({
    timestamp: time.getTime(),
    dateFormatted: moment(time).format('dddd DD MMM YYYY hh:mm a'),
    name: 'Shelia Hopper',
    hasComment: false,
    isCustomer: req.body.caller === 'customer',
    authenticated: req.body.confirmed
  })
  res.render(viewPath + '/booking/bobby_timeline')
})

router.get('/assessment-centres', function (req, res, next) {
  res.locals.centres = require(filePath + '/data/centres.js')
  next()
})

router.get('/decision_maker', function (req, res, next) {
  var customers = require(filePath + '/data/decisionMaker.js')
  res.locals.customers = customers.map(customer => {
    var arrivedTime = moment(customer.appointmentTime, 'h:mma')
    customer.timeArrived = arrivedTime.add(customer.arrivedTime, 'minutes').format('h:mma')

    return customer
  })
  next()
})

router.get('*/:customerId/appointment-details', function (req, res, next) {
  res.locals.history = appointmentHistory.filter(entry => entry._id == req.params.customerId)
  console.log(res.locals.history)
  next()
})

router.get('/booking/referrals/:customerId', function (req, res, next) {
  res.render(viewPath + '/booking/customer-referral')
})

router.get('/booking/decision/:customerId/appointment-details', function (req, res, next) {
  res.locals.history = appointmentHistory.filter(entry => entry._id === req.params.customerId)
  next()
})

router.get('/booking/:customerId', function (req, res, next) {
  res.render(viewPath + '/booking/customer-booked')
})

router.get('/booking/decision/:customerId', function (req, res, next) {
  res.render(viewPath + '/booking/customer-booked')
})

router.get('/booking/decision/:customerId/details', function (req, res, next) {
  res.render(viewPath + '/booking/details/contact')
})

router.get('/booking/decision/:customerId/illness', function (req, res, next) {
  res.render(viewPath + '/booking/details/illness')
})

router.get('/booking/decision/:customerId/gp', function (req, res, next) {
  res.render(viewPath + '/booking/details/gp')
})

router.get('/booking/decision/:customerId/details', function (req, res, next) {
  res.render(viewPath + '/booking/details/contact')
})

router.get('/booking/decision/:customerId/timeline', function (req, res, next) {
  res.render(viewPath + '/booking/timeline')
})

router.get('/booking/decision/:customerId/evidence', function (req, res, next) {
  res.render(viewPath + '/booking/evidence/index')
})

router.get('/booking/decision/:customerId/evidence/:page', function (req, res, next) {
  res.render(viewPath + '/booking/evidence/' + req.params.page)
})

router.get('/booking/arrived/:customerId', function (req, res, next) {
  res.render(viewPath + '/booking/customer-booked')
})

router.get('/booking/arrived/:customerId/appointment-details', function (req, res, next) {
  res.locals.history = appointmentHistory.filter(entry => entry._id === req.params.customerId)

  res.render(viewPath + '/booking/appointment-details')
})

router.get('/booking/arrived/:customerId/details', function (req, res, next) {
  res.render(viewPath + '/booking/details/contact')
})

router.get('/booking/arrived/:customerId/illness', function (req, res, next) {
  res.render(viewPath + '/booking/details/illness')
})

router.get('/booking/arrived/:customerId/gp', function (req, res, next) {
  res.render(viewPath + '/booking/details/gp')
})

router.get('/booking/arrived/:customerId/details', function (req, res, next) {
  res.render(viewPath + '/booking/details/contact')
})

router.get('/booking/arrived/:customerId/timeline', function (req, res, next) {
  res.render(viewPath + '/booking/timeline')
})

router.get('/booking/arrived/:customerId/evidence', function (req, res, next) {
  res.render(viewPath + '/booking/evidence/index')
})

router.get('/booking/arrived/:customerId/evidence/:page', function (req, res, next) {
  res.render(viewPath + '/booking/evidence/' + req.params.page)
})

router.get('/booking/arrived/:customerId/:pageName', function (req, res, next) {
  res.render(viewPath + '/booking/' + req.params.pageName)
})

router.get('/booking/decision/:customerId/:page', function (req, res, next) {
  res.render(viewPath + '/booking/' + req.params.page)
})

router.get('/booking/:customerId/*', function (req, res, next) {
  res.locals.customer = appointmentCustomers
                          .filter(customer => customer._id === req.params.customerId)[0]

  console.log(res.locals.customer)
  next()
})

router.get('/assessment/:customerId/*', function (req, res, next) {
  res.locals.customer = assessmentCustomers
                          .filter(customer => customer._id === req.params.customerId)[0]

  console.log(res.locals.customer)
  next()
})

router.get('/assessment/:customerId/evidence/typicalDayEdit/:commentId', function (req, res, next) {
  res.locals.comment = req.session.data.typicalDayComments.filter(item => item.id === req.params.commentId)[0]

  res.render(viewPath + '/assessment/evidence/contentEditDay')
})

router.get('/assessment/:customerId/evidence/observedBehaviourEdit/:commentId', function (req, res, next) {
  res.locals.comment = req.session.data.observedBehaviourComments.filter(item => item.id === req.params.commentId)[0]

  res.render(viewPath + '/assessment/evidence/contentEditDay')
})

router.post('/assessment/:customerId/evidence/typicalDayEdit', function (req, res, next) {
  req.session.data.typicalDayComments.map(function (item) {
    if (item.id === req.body.id) {
      item.comment = req.body.comment
    }
  })
  console.log(req.session.data.typicalDayComments)

  next()
})

router.post('/assessment/:customerId/evidence/observedBehaviourEdit', function (req, res, next) {
  req.session.data.observedBehaviourComments.map(function (item) {
    if (item.id === req.body.id) {
      item.comment = req.body.comment
    }
  })
  console.log(req.session.data.observedBehaviourComments)

  next()
})

router.get('/assessment/:customerId/evidence/socialWorkHistoryEdit/:commentId', function (req, res, next) {
  res.locals.comment = req.session.data.socialWorkComments.filter(item => item.id === req.params.commentId)[0]
  res.render(viewPath + '/assessment/evidence/contentEdit')
})

router.get('/assessment/:customerId/evidence/conditionHistoryNew/:commentId', function (req, res, next) {
  res.locals.comment = req.session.data.conditionComments.filter(item => item.id === req.params.commentId)[0]
  res.render(viewPath + '/assessment/evidence/contentEditCondition')
})

router.post('/assessment/:customerId/evidence/socialWorkHistoryEdit', function (req, res, next) {
  req.session.data.socialWorkComments.map(function (item) {
    if (item.id === req.body.id) {
      item.comment = req.body.comment
    }
  })
  console.log(req.session.data.socialWorkComments)

  next()
})

router.post('/assessment/:customerId/evidence/conditionHistoryNew', function (req, res, next) {
  req.session.data.conditionComments.map(function (item) {
    if (item.id === req.body.id) {
      item.comment = req.body.comment
    }
  })
  console.log(req.session.data.conditionComments)

  next()
})

router.post('/assessment/:customerId/evidence/socialWorkHistory', function (req, res, next) {
  if (req.body.delete == 'true') {
    req.session.data.socialWorkComments = req.session.data.socialWorkComments.filter(item => item.id != req.body.id)
  } else {
    req.session.data.socialWorkComments.push({
      id: crypto.randomBytes(16).toString('hex'),
      comment: req.body.comments,
      time: moment().format()
    })

    res.locals.comments = req.session.data.socialWorkComments
  }
  next()
})

router.post('/assessment/:customerId/evidence/typicalDay', function (req, res, next) {
  if (req.body.delete == 'true') {
    req.session.data.typicalDayComments = req.session.data.typicalDayComments.filter(item => item.id != req.body.id)
  } else {
    req.session.data.typicalDayComments.push({
      id: crypto.randomBytes(16).toString('hex'),
      comment: req.body.comments,
      time: moment().format()
    })

    res.locals.comments = req.session.data.typicalDayComments
  }
  next()
})

router.post('/assessment/:customerId/evidence/observedBehaviour', function (req, res, next) {
  if (req.body.delete == 'true') {
    req.session.data.observedBehaviourComments = req.session.data.observedBehaviourComments.filter(item => item.id != req.body.id)
  } else {
    req.session.data.observedBehaviourComments.push({
      id: crypto.randomBytes(16).toString('hex'),
      comment: req.body.comments,
      time: moment().format()
    })

    res.locals.comments = req.session.data.observedBehaviourComments
  }
  next()
})

router.post('/assessment/:customerId/evidence/conditionHistoryNew', function (req, res, next) {
  if (req.body.delete == 'true') {
    req.session.data.conditionComments = req.session.data.conditionComments.filter(item => item.id != req.body.id)
  } else {
    req.session.data.conditionComments.push({
      id: crypto.randomBytes(16).toString('hex'),
      comment: req.body.comments,
      time: moment().format()
    })

    res.locals.comments = req.session.data.conditionComments
  }
  next()
})

router.get('/assessment/:customerId/evidence/socialWorkHistory*', function (req, res, next) {
  res.locals.comments = req.session.data.socialWorkComments
  next()
})

router.get('/assessment/:customerId/evidence/typicalDay', function (req, res, next) {
  res.locals.comments = req.session.data.typicalDayComments
  next()
})

router.get('/assessment/:customerId/evidence/observedBehaviour', function (req, res, next) {
  res.locals.comments = req.session.data.observedBehaviourComments
  next()
})

router.get('/assessment/:customerId/evidence/conditionHistoryNew', function (req, res, next) {
  res.locals.comments = req.session.data.conditionComments
  next()
})

router.get('/assessment/evidence/wca-index', function (req, res, next) {
  next()
})

router.post('/assessment/evidence/wca-index', function (req, res, next) {
  req.session.data.assessmentStartTime = moment().format()
  next()
})

router.post('/assessment/evidence/medical_assessment_dashboard', function (req, res, next) {
  req.session.data.assessmentEndTime = moment().format()
  next()
})

router.get('/booking/referrals/:customerId/gp', function (req, res, next) {
  res.render(viewPath + '/booking/details/gp')
})

router.get('/booking/referrals/:customerId/illness', function (req, res, next) {
  res.render(viewPath + '/booking/details/illness')
})

router.get('/booking/referrals/:customerId/details', function (req, res, next) {
  res.render(viewPath + '/booking/details/contact')
})

router.get('/booking/referrals/:customerId/timeline', function (req, res, next) {
  res.render(viewPath + '/booking/timeline')
})

router.get('/booking/referrals/:customerId/timeline-scrutiny', function (req, res, next) {
  res.render(viewPath + '/booking/timeline-scrutiny')
})

router.get('/booking/referrals/:customerId/appointment-details', function (req, res, next) {
  res.render(viewPath + '/booking/appointment-details')
})

router.get('/booking/referrals/:customerId/evidence', function (req, res, next) {
  res.render(viewPath + '/booking/evidence/index')
})

router.get('/booking/referrals/:customerId/evidence/:page', function (req, res, next) {
  res.render(viewPath + '/booking/evidence/' + req.params.page)
})

router.get('/booking/:customerId/evidence/:page', function (req, res, next) {
  res.render(viewPath + '/booking/evidence/' + req.params.page)
})

router.get('/booking/:customerId/illness', function (req, res, next) {
  res.render(viewPath + '/booking/details/illness')
})

router.get('/booking/:customerId/gp', function (req, res, next) {
  res.render(viewPath + '/booking/details/gp')
})

router.get('/booking/:customerId/today', function (req, res, next) {
  res.render(viewPath + '/booking/details/today')
})
router.get('/booking/arrived/:customerId/send-home', function (req, res, next) {
  var appointmentTime = moment(res.locals.customer.appointmentTime, 'h:mma')
  res.locals.customer.timeArrived = appointmentTime.add(res.locals.customer.arrivedTime, 'minutes').format('h:mma')
  next()
})

router.get('/booking/:customerId/details', function (req, res, next) {
  res.render(viewPath + '/booking/details/index')
})

// router.get('/booking/:customerId/timeline', function(req, res, next){
 // res.render(viewPath +'/booking/timeline_booked');
// })

router.post('/booking/mendez/mendez_timeline-arrived', function (req, res, next) {
  res.locals.arrivedTimeMoment = moment(new Date())
  arrivedTime = res.locals.arrivedTimeMoment.format('h:mm a')
  res.locals.arrivedTime = arrivedTime

  res.render(viewPath + '/booking/mendez_timeline-arrived')
})

router.post('/booking/:customerId/timeline-arrived', function (req, res, next) {
  var customers = require(filePath + '/data/booked.js')
  res.locals.customer = customers.filter(customer => customer._id === req.params.customerId)[0]

  var arrivedTimeMoment = moment(new Date())
  res.locals.customer.timeArrived = arrivedTimeMoment.format('h:mm a')

  res.render(viewPath + '/booking/timeline-arrived')
})

router.get('/booking/mendez/*', function (req, res, next) {
  var startTime = moment(res.locals.arrivedTime, 'hh:mma')
  var endTime = moment(new Date(), 'hh:mm:ss a')

  var totalHours = (endTime.diff(startTime, 'hours'))
  var totalMinutes = endTime.diff(startTime, 'minutes')
  var clearMinutes = totalMinutes % 60
  res.locals.waitTime = totalMinutes // totalHours + " hours and " + clearMinutes + " minutes";
  next()
})

router.post('/booking/arrived/:customerId/send-home-2', function (req, res, next) {
  res.locals.postData = req.body
  var reason = req.body.otherReason || req.body.reason
  appointmentHistory.push({
    _id: req.params.customerId,
    title: 'Sent home unseen',
    comments: reason,
    entryDate: moment(new Date()).format(),
    appointmentDate: null,
    changedByCustomer: false
  })

  next()
})

router.get('/booking/:customerId/evidence', function (req, res, next) {
  res.render(viewPath + '/booking/evidence/index')
})

router.get('/booking/:customerId/:pageName', function (req, res, next) {
  res.render(viewPath + '/booking/' + req.params.pageName)
})

router.get('/capacity/manage-centre/:centreId*', function (req, res, next) {
  getCentreDetails(req, res)
  res.locals.staff = planningStaff.filter(staff => staff.homeCentre.toLowerCase() === req.params.centreId)
  next()
})

router.post('/capacity/manage-centre/:centreId*', function (req, res, next) {
  getCentreDetails(req, res)
  res.locals.staff = planningStaff.filter(staff => staff.homeCentre === req.params.centreId)
  next()
})

router.get('/capacity/manage-centre/:centreId', function (req, res, next) {
  res.render(viewPath + '/capacity/manage-centre/index')
})

router.get('/capacity/manage-centre/:centreId/:section*', function (req, res, next) {
  res.locals.selectedTab = req.params.section
  next()
})

router.post('/capacity/manage-centre/:centreId/:section*', function (req, res, next) {
  res.locals.selectedTab = req.params.section
  next()
})

router.get('/capacity/manage-centre/:centreId/manage-staff', function (req, res, next) {
  res.locals.staffTotals = {}
  res.locals.staffTotals.complex = res.locals.staff.filter(staff => staff.skill === 'Complex Neuro').length
  res.locals.staffTotals.neuro = res.locals.staff.filter(staff => staff.skill === 'Neuro').length
  res.locals.staffTotals.standard = res.locals.staff.filter(staff => staff.skill === 'Standard').length
  res.locals.staffTotals.scrutiny = res.locals.staff.filter(staff => staff.scrutinyPaperwork).length
  res.locals.staffTotals.total = res.locals.staff.length

  //
  res.render(viewPath + '/capacity/manage-staff/index')
})

router.get('/capacity/manage-centre/:centreId/manage-staff/staff-profile/:staffId*', function (req, res, next) {
  var staff = planningStaff

  res.locals.centres = require(filePath + '/data/centres.js')
  console.log(res.locals.centres)

  res.locals.person = staff.filter(person => person.id === req.params.staffId)[0]
  var today = moment(new Date())
  res.locals.displayMonth = today.format('MMMM YYYY')
  var year = today.year()
  var month = today.month() + 1
  res.locals.calendar = new calendar.Calendar(0).monthdatescalendar(year, month)
  console.log(res.locals.calendar[0])
  res.locals.today = today.format()
  next()
})

router.post('/capacity/manage-centre/:centreId/manage-staff/staff-profile/:staffId*', function (req, res, next) {
  var staff = require(filePath + '/data/staff.js')
  res.locals.centres = require(filePath + '/data/centres.js')

  res.locals.person = staff.filter(person => person.id === req.params.staffId)[0]
  var today = moment(new Date(2018, 8, 9))
  var year = today.year()
  var month = today.month() + 1
  res.locals.calendar = new calendar.Calendar(0).monthdatescalendar(2018, 8)
  res.locals.today = today.format()
  next()
})

router.post('/capacity/manage-centre/:centreId/manage-staff/staff-profile/:staffId/staff-availability-2', function (req, res, next) {
  res.locals.formData = req.body
  res.render(viewPath + '/capacity/manage-staff/staff-availability-2')
})

router.post('/capacity/manage-centre/:centreId/manage-staff/staff-profile/:staffId/staff-profile-2', function (req, res, next) {
  res.locals.formData = req.body

  res.render(viewPath + '/capacity/manage-staff/staff-profile-2')
})

router.get('/capacity/manage-centre/:centreId/capacity-overbooked', function (req, res, next) {
  res.locals.staff = require(filePath + '/data/staff-overbooked.js')

  next()
})

router.get('/capacity/manage-centre/:centreId', function (req, res, next) {
  res.render(viewPath + '/capacity/manage-centre/index')
})

router.get('/capacity/manage-centre/:centreId/:section*', function (req, res, next) {
  res.locals.selectedTab = req.params.section
  next()
})

router.get('/capacity/manage-centre/:centreId/manage-staff', function (req, res, next) {
  res.locals.staffTotals = {}
  res.locals.staffTotals.complex = res.locals.staff.filter(staff => staff.skill === 'Complex Neuro').length
  res.locals.staffTotals.neuro = res.locals.staff.filter(staff => staff.skill === 'Neuro').length
  res.locals.staffTotals.standard = res.locals.staff.filter(staff => staff.skill === 'Standard').length
  res.locals.staffTotals.scrutiny = res.locals.staff.filter(staff => staff.scrutinyPaperwork).length
  res.locals.staffTotals.total = res.locals.staff.length

  //
  res.render(viewPath + '/capacity/manage-staff/inde')
})

router.get('/capacity/manage-centre/:centreId/manage-staff/staff-profile/:staffId', function (req, res, next) {
  res.render(viewPath + '/capacity/manage-staff/staff-profile')
})

router.get('/capacity/manage-centre/:centreId/manage-staff/staff-profile/:staffId/:section', function (req, res, next) {
  res.render(viewPath + '/capacity/manage-staff/' + req.params.section)
})

router.get('/capacity/manage-centre/:centreId/capacity-overbooked', function (req, res, next) {
  res.locals.staff = require(filePath + '/data/staff-overbooked.js')

  next()
})

router.get('/capacity/manage-centre/:centreId/capacity*', function (req, res, next) {
  res.locals.selectedTab = 'capacity'

  res.locals.staffTotals = {}
  res.locals.staffTotals.available = res.locals.staff.filter(function (obj) {
    if (obj.scrutinyPaperwork && obj.days[req.query.day].scrutiny) {
      return false
    } else {
      return obj.days[req.query.day].available
    }
  }).length

  var totalAppointments = 0

  slotsData[req.query.day].map(day => totalAppointments = totalAppointments + day.usedSlots)
  res.locals.totalAppointments = totalAppointments
  res.locals.slots = slotsData[req.query.day]
  res.locals.totalSlots = slotsData[req.query.day].length

  res.locals.totalAvailableAppointments = res.locals.staffTotals.available * res.locals.totalSlots
  res.render("fha/v' + versionNumber +'/capacity/manage-centre/capacity")
})

router.get('/capacity/manage-centre/:centreId/details', function (req, res, next) {
  res.render(viewPath + '/capacity/manage-centre/index')
})

router.get('/capacity/manage-centre/:centreId/slots', function (req, res, next) {
  res.render(viewPath + '/capacity/manage-centre/index')
})
router.get('/capacity/manage-centre/:centreId/rooms', function (req, res, next) {
  res.render(viewPath + '/capacity/manage-centre/index')
})

router.get('/capacity/manage-centre/:centreId/:section', function (req, res, next) {
  res.render(viewPath + '/capacity/manage-centre/' + req.params.section)
})

router.post('/capacity/manage-centre/:centreId/manage-staff/new-staff-skill', function (req, res, next) {
  res.locals.person = {
    name: req.body.name,
    phone: req.body.phone,
    mobile: req.body.mobile,
    email: req.body.email
  }
  res.render(viewPath + '/capacity/manage-staff/new-staff-skill')
})

router.post('/capacity/manage-centre/:centreId/manage-staff/new-staff-hours', function (req, res, next) {
  res.locals.person = {
    name: req.body.name,
    phone: req.body.phone,
    mobile: req.body.mobile,
    email: req.body.email,
    scrutiny: req.body.scrutiny,
    skill: req.body.skill
  }
  res.render(viewPath + '/capacity/manage-staff/new-staff-hours')
})

router.post('/assessment-centres', function (req, res, next) {
  res.locals.centres = require(filePath + '/data/centres.js')
  var centre = {
    name: req.body.name,
    location: req.body.location
  }
  res.locals.centres[centre.name] = centre
  res.render(viewPath + '/assessment-centres')
})

router.post('/capacity/new-centre-2', function (req, res, next) {
  res.locals.centre = {
    name: req.body.name,
    location: req.body.location
  }
  res.render(viewPath + '/capacity/new-centre-2')
})

router.post('/capacity/new-centre-3', function (req, res, next) {
  res.locals.centre = {
    name: req.body.name,
    location: req.body.location
  }
  res.render(viewPath + '/capacity/new-centre-3')
})

router.post('/capacity/manage-centre/:centreId/manage-staff/', function (req, res, next) {
  var scrutiny = req.body.scrutiny === 'true'
  res.locals.person = {
    name: req.body.name,
    phone: req.body.phone,
    mobile: req.body.mobile,
    email: req.body.email,
    scrutinyPaperwork: scrutiny,
    skill: req.body.skill
  }
  res.locals.staff.push(res.locals.person)
  res.locals.query.tab = 'staff'

  res.locals.staffTotals = {}
  res.locals.staffTotals.complex = res.locals.staff.filter(staff => staff.skill === 'Complex Neuro').length
  res.locals.staffTotals.neuro = res.locals.staff.filter(staff => staff.skill === 'Neuro').length
  res.locals.staffTotals.standard = res.locals.staff.filter(staff => staff.skill === 'Standard').length
  res.locals.staffTotals.scrutiny = res.locals.staff.filter(staff => staff.scrutinyPaperwork).length
  res.locals.staffTotals.total = res.locals.staff.length

  res.render(viewPath + '/capacity/manage-staff/index')
})

router.get('/capacity/manage-centre/:centreId/manage-staff/:section', function (req, res, next) {
  res.render(viewPath + '/capacity/manage-staff/' + req.params.section)
})

router.post('/capacity/manage-centre/:centreId/edit-centre-3', function (req, res, next) {
  if (req.body['available-days-Saturday'] === 'on') {
    res.locals.saturday = true
  } else {
    res.locals.saturday = false
  }
  res.render(viewPath + '/capacity/manage-centre/edit-centre-3')
})

router.post('/capacity/manage-centre/:centreId/details', function (req, res, next) {
  res.locals.centre.details = req.body.details
  if (req.body.saturday == 'true') {
    res.locals.centre.openingTimes[5] = {
      'day': 'Saturday',
      'open': '10:00am - 3:00pm'
    }
  } else {
    res.locals.centre.openingTimes[5] = {
      'day': 'Saturday',
      'open': 'Closed'
    }
  }
  res.render(viewPath + '/capacity/manage-centre/index')
})

router.get('/capacity/manage-centre/capacity', function (req, res, next) {
  res.locals.staffTotals = {}
  res.locals.staffTotals.available = staffData.filter(function (obj) {
    if (obj.scrutinyPaperwork && obj.days[req.query.day].scrutiny) {
      return false
    } else {
      return obj.days[req.query.day].available
    }
  }).length

  var totalAppointments = 0

  slotsData[req.query.day].map(day => totalAppointments = totalAppointments + day.usedSlots)
  res.locals.totalAppointments = totalAppointments
  res.locals.slots = slotsData[req.query.day]
  res.locals.totalSlots = slotsData[req.query.day].length

  res.locals.totalAvailableAppointments = res.locals.staffTotals.available * res.locals.totalSlots

  next()
})

router.get('/capacity/manage-centre/capacity-edit-slots', function (req, res, next) {
  res.locals.staffTotals = {}
  res.locals.staffTotals.available = staffData.filter(function (obj) {
    if (obj.scrutinyPaperwork && obj.days[req.query.day].scrutiny) {
      return false
    } else {
      return obj.days[req.query.day].available
    }
  }).length

  var totalAppointments = 0

  slotsData[req.query.day].map(day => totalAppointments = totalAppointments + day.usedSlots)
  res.locals.totalAppointments = totalAppointments
  res.locals.slots = slotsData[req.query.day]
  res.locals.totalSlots = slotsData[req.query.day].length

  res.locals.totalAvailableAppointments = res.locals.staffTotals.available * res.locals.totalSlots
  next()
})

router.get('/capacity/manage-centre/capacity-holiday', function (req, res, next) {
  res.locals.staff = staffDataHoliday
  res.locals.staffTotals = {}
  res.locals.staffTotals.available = staffDataHoliday.filter(function (obj) {
    if (obj.scrutinyPaperwork && obj.days[req.query.day].scrutiny) {
      return false
    } else {
      return obj.days[req.query.day].available
    }
  }).length

  var totalAppointments = 0

  slotsData[req.query.day].map(day => totalAppointments = totalAppointments + day.usedSlots)
  res.locals.totalAppointments = totalAppointments
  res.locals.slots = slotsData[req.query.day]
  res.locals.totalSlots = slotsData[req.query.day].length

  res.locals.totalAvailableAppointments = res.locals.staffTotals.available * res.locals.totalSlots

  next()
})

router.get('/capacity/manage-centre/capacity-2', function (req, res, next) {
  res.locals.staff = staffData2
  res.locals.staffTotals = {}
  res.locals.staffTotals.available = staffData2.filter(function (obj) {
    if (obj.scrutinyPaperwork && obj.days[req.query.day].scrutiny) {
      return false
    } else {
      return obj.days[req.query.day].available
    }
  }).length

  var totalAppointments = 0

  slotsData2[req.query.day].map(day => totalAppointments = totalAppointments + day.usedSlots)
  res.locals.totalAppointments = totalAppointments
  res.locals.slots = slotsData2[req.query.day]
  res.locals.totalSlots = slotsData2[req.query.day].length

  if (req.query.day == 'thursday') {
    res.locals.totalAvailableAppointments = res.locals.staffTotals.available * res.locals.totalSlots - 11
  } else {
    res.locals.totalAvailableAppointments = res.locals.staffTotals.available * res.locals.totalSlots
  }
  next()
})

router.get('/assessment/:customerId/general-observations', function (req, res, next) {
  res.locals.comments = req.session.data.observations
  next()
})

router.get('/assessment/:customerId/scoring/report-view', function (req, res, next) {
  res.locals.comments = req.session.data.observations
  next()
})

router.post('/assessment/:customerId/general-observations-post', function (req, res, next) {
  var time = new Date()
  res.locals.comments = req.session.data.observations

  res.locals.comments.push({
    comment: req.body.comment,
    timestamp: time.getTime(),
    dateFormatted: moment(time).format('dddd DD MMM YYYY hh:mm a'),
    name: 'Heather Harrison',
    hasComment: true,
    isCustomer: true
  })
  res.redirect(301, '/fha/v' + versionNumber + '/assessment/' + req.params.customerId + '/general-observations')
})

router.get('/planning/*', function (req, res, next) {
  next()
})

var planningCentres = require(filePath + '/data/capacity/monday.js')
var planningStaff = require(filePath + '/data/capacity/allocatedStaff.js').filter(staff => staff.allocatedCentre !== '')

var resetCentres = function () {
  planningCentres.forEach(function (centre) {
    centre.morning = {
      reviews: [],
      assessments: [],
      complex: 0,
      neuro: [],
      review: []
    }

    centre.afternoon = {
      assessments: [],
      reviews: [],
      complex: 0,
      neuro: [],
      review: []
    }

    centre.allocatedStaff = []

    centre.complex = 0
    planningStaff.forEach(function (staff) {
      if (staff.allocatedCentre == centre.name) {
        centre.allocatedStaff.push(staff)
        if (staff.morning != 'unnavailable') {
          centre.morning[staff.morning].push(staff)
          if (staff.complexNeuro) {
            centre.morning.complex ++
          }
        }
        if (staff.afternoon != 'unnavailable') {
          centre.afternoon[staff.afternoon].push(staff)
          if (staff.complexNeuro) {
            centre.afternoon.complex ++
          }
        }
      }
    })
  })
}

router.get('/planning/day/:day', function (req, res, next) {
  resetCentres(req, res)

  res.locals.centres = planningCentres

  res.render(viewPath + '/planning/area-day')
})

router.get('/planning/centre/:centre', function (req, res, next) {
  resetCentres(req, res)

  res.locals.centre = planningCentres.filter(centre => centre.name == req.params.centre)[0]

  res.locals.staff = res.locals.centre.allocatedStaff
  res.locals.centreName = req.params.centre
  res.render(viewPath + '/planning/assigned-staff')
})

router.get('/planning/reassign/:centre/:staffId', function (req, res, next) {
  res.locals.centre = planningCentres.filter(centre => centre.name == req.params.centre)[0]

  res.locals.staff = planningStaff.filter(staff => staff.id === req.params.staffId)[0]

  res.render(viewPath + '/planning/reassign')
})

router.post('/planning/centre/:centre', function (req, res, next) {
  planningStaff.map(staff => {
    if (req.body.staffId === staff.id) {
      console.log(staff)
      staff.morning = req.body.morning || staff.morning
      staff.afternoon = req.body.afternoon || staff.afternoon
      staff.allocatedCentre = req.body.location

      console.log(staff)
    }
  })

  next()
})

var reviewCustomers = require(filePath + '/data/reviews/readyForReview.js')

router.get('/review', function (req, res, next) {
  res.locals.customers = reviewCustomers
  next()
})

router.get('/ready-for-review', function (req, res, next) {
  res.locals.customers = reviewCustomers
                            .filter(customer => customer.status === 'review')
  next()
})

router.post('/ready-for-review', function (req, res, next) {
  var body = req.body
  req.session.data['filter'] = '';
  res.locals.customers = reviewCustomers
    .filter(customer => customer.status === 'review')
  if (body.filter) {
    req.session.data['filter'] = body.filter;
    let filters = Array.isArray(body.filter) ? body.filter : [ body.filter ];

    res.locals.customers = res.locals.customers.filter(function (e) {
      for (let i = 0; i < filters.length; i++) {
        if (e.tags.includes(filters[i])) {
          return true
        }
      }
      return false
    })
  }
  res.render(viewPath + '/ready-for-review')
})

router.get('/requested-medical-evidence', function (req, res, next) {
  res.locals.customers = reviewCustomers
                            .filter(customer => customer.status === 'fme')
  next()
})

router.get('/scrutiny/:customerId/*', function (req, res, next) {
  res.locals.customer = reviewCustomers
                          .filter(customer => customer._id === req.params.customerId)[0]

  next()
})

router.get('/security/:customerId/*', function (req, res, next) {
  res.locals.customer = appointmentCustomers
                          .filter(customer => customer._id === req.params.customerId)[0]

  next()
})

router.get('/scrutiny/:customerId/details', function (req, res, next) {
  res.render(viewPath + '/scrutiny/details/index')
})

router.get('/scrutiny/:customerId/details/:pageName', function (req, res, next) {
  res.render(viewPath + '/scrutiny/details/' + req.params.pageName)
})

router.get('/scrutiny/:customerId/evidence', function (req, res, next) {
  res.render(viewPath + '/scrutiny/evidence/index')
})

router.get('/scrutiny/:customerId/evidence/:pageName', function (req, res, next) {
  res.render(viewPath + '/scrutiny/evidence/' + req.params.pageName)
})

router.get('/assessment/:customerId/evidence/socialWorkHistoryEdit/:pageName', function (req, res, next) {
  res.render(viewPath + '/assessment/evidence/socialWorkHistoryEdit' + req.params.pageName)
})

router.get('/scrutiny/:customerId/:pageName', function (req, res, next) {
  res.render(viewPath + '/scrutiny/' + req.params.pageName)
})

router.get('/security/:customerId/:pageName', function (req, res, next) {
  res.render(viewPath + '/security/' + req.params.pageName)
})

router.post('/scrutiny/:customerId/fme-confirm', function (req, res, next) {
  reviewCustomers.map(customer => {
    if (customer._id === req.params.customerId) {
      customer.fmeRequestedDate = moment().format()
      customer.fmeType = req.session.data.type
      customer.status = 'fme'

      delete req.session.data.type

      console.log(customer)
    }
  })

  res.redirect(301, '/fha/v' + versionNumber + '/scrutiny/' + req.params.customerId + '/timeline')
})

/// Decision maker routes ------------------------------------------------------------------------//
var dmCustomers = require(filePath + '/data/dm/dm.js')

router.get('/decision-maker', function (req, res, next) {
  res.locals.customers = dmCustomers

  next()
})

router.get('/decisionmaker/:customerId/*', function (req, res, next) {
  res.locals.customer = dmCustomers
                          .filter(customer => customer._id === req.params.customerId)[0]

  console.log(res.locals.customer)
  next()
})

router.get('/decisionmaker/:customerId/timeline', function (req, res, next) {
  res.render(viewPath + '/decisionmaker/timeline')
})

router.get('/decisionmaker/:customerId/appointment', function (req, res, next) {
  res.render(viewPath + '/decisionmaker/appointment')
})

router.get('/decisionmaker/:customerId/evidence', function (req, res, next) {
  res.render(viewPath + '/decisionmaker/evidence/index')
})

router.get('/decisionmaker/:customerId/decision', function (req, res, next) {
  res.render(viewPath + '/decisionmaker/decision/index')
})

router.get('/decisionmaker/:customerId/decision/:pageName', function (req, res, next) {
  res.render(viewPath + '/decisionmaker/decision/' + req.params.pageName)
})

router.get('/decisionmaker/:customerId/details', function (req, res, next) {
  res.render(viewPath + '/decisionmaker/details/index')
})

router.get('/decisionmaker/:customerId/details/:pageName', function (req, res, next) {
  res.render(viewPath + '/decisionmaker/details/' + req.params.pageName)
})

/// END decision maker routes ------------------------------------------------------------------------//

router.get('/assessment-reports', function (req, res, next) {
  res.locals.customers = dmCustomers
  .filter(customer => customer.status === 'Assessment reports')
  next()
})

router.get('/failed-to-attend', function (req, res, next) {
  res.locals.customers = dmCustomers
  .filter(customer => customer.status === 'Failed to attend appointment')
  next()
})

router.post('/failed-to-attend', function (req, res, next) {
  var body = req.body
  req.session.data['filter'] = '';
  res.locals.customers = dmCustomers
    .filter(customer => customer.status === 'Failed to attend appointment')
  if (body.filter) {
    req.session.data['filter'] = body.filter;
    let filters = Array.isArray(body.filter) ? body.filter : [ body.filter ];

    res.locals.customers = res.locals.customers.filter(function (e) {
      for (let i = 0; i < filters.length; i++) {
        if (e.tags.includes(filters[i])) {
          return true
        }
      }
      return false
    })
  }
  res.render(viewPath + '/failed-to-attend')
})

router.get('/fta-ready-for-decision', function (req, res, next) {
  res.locals.customers = dmCustomers
  .filter(customer => customer.substatus === 'Ready for decision')
  next()
})

router.get('/fta-request-reason', function (req, res, next) {
  res.locals.customers = dmCustomers
  .filter(customer => customer.substatus === 'Request a reason')
  next()
})

router.get('/fta-record-reason', function (req, res, next) {
  res.locals.customers = dmCustomers
  .filter(customer => customer.substatus === 'Record a reason')
  next()
})

router.get('/good-cause', function (req, res, next) {
  res.locals.customers = dmCustomers
  .filter(customer => customer.status === 'Questionnaire not returned')
  next()
})

var assessmentCustomers = require(filePath + '/data/assessment/readyForAssessment.js')

router.get('/assessment', function (req, res, next) {
  res.locals.customers = assessmentCustomers

  next()
})

router.get('/ready-for-assessment', function (req, res, next) {
  res.locals.customers = assessmentCustomers
                            .filter(customer => customer.status === 'Ready for assessment')
  next()
})

router.get('/assessment-stopped', function (req, res, next) {
  res.locals.customers = assessmentCustomers
                            .filter(customer => customer.status === 'Assessment stopped')
  next()
})

router.get('/completed-assessments', function (req, res, next) {
  res.locals.customers = assessmentCustomers
                            .filter(customer => customer.status === 'Assessment completed')
  next()
})

router.get('/todays-appointments', function (req, res, next) {
  res.locals.customers = assessmentCustomers
                            .filter(customer => customer.status === 'Appointment today')
  next()
})

router.get('/ready-to-book', function (req, res, next) {
  res.locals.customers = assessmentCustomers
                            .filter(customer => customer.status === 'Ready to book')
  next()
})

router.get('/booked', function (req, res, next) {
  res.locals.customers = assessmentCustomers
                            .filter(customer => customer.status === 'Booked')
  next()
})

router.get('/assessment/:customerId/assessment*', function (req, res, next) {
  res.locals.customer = assessmentCustomers
                          .filter(customer => customer._id === req.params.customerId)[0]

  console.log(res.locals.customer)
  next()
})

router.get('/assessment/:customerId/details', function (req, res, next) {
  res.render(viewPath + '/assessment/details/index')
})

router.get('/assessment/:customerId/details/:pageName', function (req, res, next) {
  res.render(viewPath + '/assessment/details/' + req.params.pageName)
})

router.get('/assessment/:customerId/evidence', function (req, res, next) {
  res.render(viewPath + '/assessment/evidence/index')
})

router.get('/assessment/:customerId/evidence/:pageName', function (req, res, next) {
  res.render(viewPath + '/assessment/evidence/' + req.params.pageName)
})

router.get('/assessment/:customerId/dashboard', function (req, res, next) {
  res.render(viewPath + '/assessment/evidence/illnessEffects')
})

router.get('/assessment/:customerId/scoring', function (req, res, next) {
  res.render(viewPath + '/assessment/scoring/index')
})

router.get('/assessment/:customerId/scoring/:pageName', function (req, res, next) {
  res.render(viewPath + '/assessment/scoring/' + req.params.pageName)
})

router.post('/assessment/:customerId/ready-for-recommendation', function (req, res, next) {
  assessmentCustomers.map(customer => {
    if (customer._id === req.params.customerId) {
      customer.status = 'Ready for recommendation'

      delete req.session.data.type

      console.log(customer)
    }
  })

  res.redirect(301, '/fha/v' + versionNumber + '/assessment/' + req.params.customerId + '/evidence/medical_assessment_dashboard')
})

router.post('/assessment/:customerId/completed-assessment', function (req, res, next) {
  assessmentCustomers.map(customer => {
    if (customer._id === req.params.customerId) {
      customer.status = 'Assessment completed'

      delete req.session.data.type

      console.log(customer)
    }
  })

  res.redirect(301, '/fha/v' + versionNumber + '/assessment/' + req.params.customerId + '/scoring/report-print')
})

router.post('/assessment/:customerId/ready-for-assessment', function (req, res, next) {
  assessmentCustomers.map(customer => {
    if (customer._id === req.params.customerId) {
      customer.status = 'Ready for assessment'

      delete req.session.data.type

      console.log(customer)
    }
  })

  res.redirect(301, '/fha/v' + versionNumber + '/assessment/' + req.params.customerId + '/timeline')
})

router.post('/assessment/:customerId/todays-appointments', function (req, res, next) {
  assessmentCustomers.map(customer => {
    if (customer._id === req.params.customerId) {
      customer.status = 'Appointment today'

      delete req.session.data.type

      console.log(customer)
    }
  })

  res.redirect(301, '/fha/v' + versionNumber + '/assessment/' + req.params.customerId + '/timeline')
})

router.post('/assessment/:customerId/booked', function (req, res, next) {
  assessmentCustomers.map(customer => {
    if (customer._id === req.params.customerId) {
      customer.status = 'Booked'

      delete req.session.data.type

      console.log(customer)
    }
  })

  res.redirect(301, '/fha/v' + versionNumber + '/assessment/' + req.params.customerId + '/timeline')
})

router.post('/assessment/:customerId/ready-to-book', function (req, res, next) {
  assessmentCustomers.map(customer => {
    if (customer._id === req.params.customerId) {
      customer.status = 'Ready to book'

      delete req.session.data.type

      console.log(customer)
    }
  })

  res.redirect(301, '/fha/v' + versionNumber + '/assessment/' + req.params.customerId + '/timeline')
})

router.get('/assessment/:customerId/descriptor-:descriptorName', function (req, res, next) {
  assessmentCustomers.map(customer => {
    if (customer._id === req.params.customerId) {
      customer.descriptor = req.params.descriptorName
      console.log(customer)
    }
  })

  res.render(viewPath + '/assessment/scoring/moving1')
})

router.get('/assessment/:customerId/:pageName', function (req, res, next) {
  res.render(viewPath + '/assessment/' + req.params.pageName)
})

router.post('/scrutiny/:customerId/booking-post', function (req, res, next) {
  var bookingCustomers = require(filePath + '/data/referrals.js')

  res.locals.customer.receivedDate = moment().format()
  bookingCustomers.push(res.locals.customer)

  reviewCustomers = reviewCustomers.filter(customer => customer._id !== req.params.customerId)

  res.redirect(301, '/fha/v' + versionNumber + '/booking/referrals/' + req.params.customerId + '/timeline-scrutiny')
})

router.get('/planning/*', function (req, res, next) {
  next()
})

var planningCentres = require(filePath + '/data/capacity/monday.js')
var planningStaff = require(filePath + '/data/capacity/allocatedStaff.js').filter(staff => staff.allocatedCentre !== '')

var resetCentres = function () {
  planningCentres.forEach(function (centre) {
    centre.morning = {
      reviews: [],
      assessments: [],
      complex: 0,
      neuro: [],
      review: []
    }

    centre.afternoon = {
      assessments: [],
      reviews: [],
      complex: 0,
      neuro: [],
      review: []
    }

    centre.allocatedStaff = []

    centre.complex = 0
    planningStaff.forEach(function (staff) {
      if (staff.allocatedCentre == centre.name) {
        centre.allocatedStaff.push(staff)
        if (staff.morning != 'unnavailable') {
          centre.morning[staff.morning].push(staff)
          if (staff.complexNeuro) {
            centre.morning.complex ++
          }
        }
        if (staff.afternoon != 'unnavailable') {
          centre.afternoon[staff.afternoon].push(staff)
          if (staff.complexNeuro) {
            centre.afternoon.complex ++
          }
        }
      }
    })
  })
}

router.get('/planning/day/:day', function (req, res, next) {
  resetCentres(req, res)

  res.locals.centres = planningCentres

  res.render(viewPath + '/planning/area-day')
})

router.get('/planning/centre/:centre', function (req, res, next) {
  resetCentres(req, res)

  res.locals.centre = planningCentres.filter(centre => centre.name == req.params.centre)[0]

  res.locals.staff = res.locals.centre.allocatedStaff
  res.locals.centreName = req.params.centre
  res.render(viewPath + '/planning/assigned-staff')
})

router.get('/planning/reassign/:centre/:staffId', function (req, res, next) {
  res.locals.centre = planningCentres.filter(centre => centre.name == req.params.centre)[0]

  res.locals.staff = planningStaff.filter(staff => staff.id === req.params.staffId)[0]

  res.render(viewPath + '/planning/reassign')
})

router.post('/planning/centre/:centre', function (req, res, next) {
  planningStaff.map(staff => {
    if (req.body.staffId === staff.id) {
      console.log(staff)
      staff.morning = req.body.morning || staff.morning
      staff.afternoon = req.body.afternoon || staff.afternoon
      staff.allocatedCentre = req.body.location

      console.log(staff)
    }
  })

  next()
})

router.post('/search-results-id', function (req, res, next) {
  var sanitizeField = function (string) {
    return string.replace(/\s/g, '').toUpperCase()
  }
  var NINO = req.body.search.trim('')
  res.locals.customers = appointmentCustomers
          .filter(customer => sanitizeField(customer.NINO) === sanitizeField(req.body.search))

  res.locals.searchField = req.body.search
  res.render(viewPath + '/search-results-id')
})

router.post('/search-results', function (req, res, next) {
  var sanitizeField = function (string) {
    return string.replace(/\s/g, '').toUpperCase()
  }
  var NINO = req.body.search.trim('')
  res.locals.customers = reviewCustomers
          .filter(customer => sanitizeField(customer.NINO) === sanitizeField(req.body.search))

  res.locals.searchField = req.body.search
  res.render(viewPath + '/search-results')
})

router.post('/assessment/:customerId/evidence/mentalHealthAssessment', function (req, res, next) {
  var mentalHealthFields = [
    'Appearance',
    'Behaviour',
    'Speech',
    'Mood',
    'Cognition',
    'General',
    'Insight',
    'Thoughts',
    'Perceptions',
    'Addiction',
    'Involentry-movements',
    'Cognative-test']
  var count = 0
  mentalHealthFields.forEach(function (mhelement, index) {
    if (req.session.data[mhelement]) {
      count++
    }
    req.session.data.mentalHealthCount = count
    console.log('Mental Health count: ' + count)
    next()
  })
})

router.post('/decisionmaker/:customerId/decision/timeline', function (req, res) {
  var balls = req.session.data['whatcando']

  if (balls == 'newappointment') {
    res.redirect('/fha/v' + versionNumber + '/decisionmaker/' + req.params.customerId + '/timeline')
  } else {
    res.redirect('/fha/v' + versionNumber + '/decisionmaker/' + req.params.customerId + '/decision/close-reason')
  }
})

router.get('/send-home-book', function (req, res) {
  var locale = 'en-GB'

  res.render('location-picker-8', {
   // html_lang: 'en',
    // graph: locationServiceV3.locationGraph,
    // locations: locationServiceV3.canonicalLocationList(locale),
    // reverseMap: locationServiceV3.locationReverseMap(locale),
    // locale: locale
  })
})

/// appointment data -------

var appointmentCustomers = require(filePath + '/data/appointment/appointments.js')

router.get('/appointments', function (req, res, next) {
  res.locals.customers = appointmentCustomers

  next()
})

router.get('/did-not-attend', function (req, res, next) {
  res.locals.customers = appointmentCustomers
                            .filter(customer => customer.status === 'Did not attend')
  next()
})

router.get('/ready-to-book', function (req, res, next) {
  res.locals.customers = appointmentCustomers
                            .filter(customer => customer.status === 'Ready to book')
  next()
})

router.get('/booked-appointments', function (req, res, next) {
  res.locals.customers = appointmentCustomers
                            .filter(customer => customer.status === 'Booked')
  next()
})

router.get('/"date": "06 2017"', function (req, res, next) {
  res.locals.customers = appointmentCustomers
                            .filter(customer => customer.status === 'Ready to book')
  next()
})

router.get('/booking/:customerId/evidence', function (req, res, next) {
  res.render(viewPath + '/booking/details/index')
})

router.get('/booking/:customerId/details/:pageName', function (req, res, next) {
  res.render(viewPath + '/booking/details/' + req.params.pageName)
})

router.get('/priority-booking', function (req, res, next) {
  res.locals.customers = appointmentCustomers
  .filter(customer => customer.substatus === 'Priority booking')
  next()
})

router.get('/welfare-call-required', function (req, res, next) {
  res.locals.customers = appointmentCustomers
  .filter(customer => customer.substatus === 'Wellfair call required')
  next()
})

/// end appointment data -------

module.exports = router


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.diff.actions;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.diff.impl.DiffPanelImpl;
import com.intellij.openapi.project.DumbAware;
import org.jetbrains.annotations.NotNull;

/**
 * @author yole
 */
public class FocusOppositePaneAction extends AnAction implements DumbAware {
  public FocusOppositePaneAction() {
    setEnabledInModalContext(true);
  }

  @Override
  public void actionPerformed(@NotNull final AnActionEvent e) {
    final DiffPanelImpl diffPanel = DiffPanelImpl.fromDataContext(e.getDataContext());
    assert diffPanel != null;
    diffPanel.focusOppositeSide();
  }

  @Override
  public void update(@NotNull final AnActionEvent e) {
    final DiffPanelImpl diffPanel = DiffPanelImpl.fromDataContext(e.getDataContext());
    e.getPresentation().setEnabled(diffPanel != null);
  }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * Package for nonblocking cash implementation.
 * @author Eugene Lazarev mailto(helycopternicht@rambler.ru)
 * @since 27.07.17
 */
package ru.elazarev.nonblocking;


text:
import os, sys, json, yaml
import optparse

if __name__ == '__main__':
	parser = optparse.OptionParser()
	parser.add_option('--output', dest='output', default=None, help='output JSON filename')
	parser.add_option('--class-names', dest='class_names', help='YAML metadata for class names')
	parser.add_option('--debug-commands', dest='debug_commands', help='YAML metadata for debug commands')
	parser.add_option('--debug-errors', dest='debug_errors', help='YAML metadata for debug protocol error codes')
	parser.add_option('--opcodes', dest='opcodes', help='YAML metadata for opcodes')
	(opts, args) = parser.parse_args()

	res = {}
	def merge(fn):
		with open(fn, 'rb') as f:
			doc = yaml.load(f)
		for k in doc.keys():
			res[k] = doc[k]

	merge(opts.class_names)
	merge(opts.debug_commands)
	merge(opts.debug_errors)
	merge(opts.opcodes)

	with open(opts.output, 'wb') as f:
		f.write(json.dumps(res, indent=4) + '\n')
	print('Wrote merged debugger metadata to ' + str(opts.output))


text:
layout: default
title: Home
comments: True
---

{% include comments_count.html %}

  {% for post in paginator.posts %}

        {{ post.title }}

    {{ post.date | date_to_string }}

        {{ post.excerpt }}
        {{ site.theme.str_continue_reading }}

           Comments

  {% endfor %}

  {% if paginator.next_page %}
    Older
  {% else %}
    Older
  {% endif %}
  {% if paginator.previous_page %}
    {% if paginator.page == 2 %}
      Newer
    {% else %}
      Newer
    {% endif %}
  {% else %}
    Newer
  {% endif %}


text:
Shindo.tests("Fog::Softlayer[:product] | package_items_test", ["softlayer"]) do

  @sl = Fog::Softlayer[:product]

  tests('success') do
    # should be an empty array
    tests("#get_package_items") do
      tests("for id 0") do
        data_matches_schema(Array) { @sl.get_package_items(0).body}
        returns(261) { @sl.get_package_items(0).body.size}
      end

      tests("for id 242") do
        data_matches_schema(Array) { @sl.get_package_items(242).body}
        returns(28) { @sl.get_package_items(242).body.size}
      end
    end
  end
end


text:
from neutron_lib.api.definitions import segment
from neutron_lib.api.definitions import subnet_segmentid_writable
from neutron_lib.tests.unit.api.definitions import base

class SubnetSegmentIDDefinitionTestCase(base.DefinitionBaseTestCase):
    extension_module = subnet_segmentid_writable
    extension_attributes = (segment.SEGMENT_ID,)


text:
from FontNameToDisplayNameTransformer import FontNameToDisplayNameTransformer
from Foundation import *
from AppKit import *
from PyObjCTools.KeyValueCoding import *

class PreferencesPanelController (NSWindowController):

    @objc.IBAction
    def changeTextFont_(self, sender):
        "The user changed the current font selection, so update the default font"

        # Get font name and size from user defaults
        defaults = NSUserDefaultsController.sharedUserDefaultsController().values()
        fontName = getKey(defaults, u'FontName')
        fontSize = getKey(defaults, u'FontSize')

        # Create font from name and size; initialize font panel
        font = NSFont.fontWithName_size_(fontName, fontSize)
        if font is None:
            font = NSFont.systemFontOfSize_(NSFont.systemFontSize())
        NSFontManager.sharedFontManager().setSelectedFont_isMultiple_(font, False)
        NSFontManager.sharedFontManager().orderFrontFontPanel_(self)

        # Set window as firstResponder so we get changeFont: messages
        self.window().makeFirstResponder_(self.window())

    @objc.IBAction
    def changeFont_(self, sender):
        "This is the message the font panel sends when a new font is selected"
        # Get selected font
        fontManager = NSFontManager.sharedFontManager()
        selectedFont = fontManager.selectedFont()
        if selectedFont is None:
            selectedFont = NSFont.systemFontOfSize_(NSFont.systemFontSize())
        panelFont = fontManager.convertFont_(selectedFont)

        # Get and store details of selected font
        # Note: use fontName, not displayName.  The font name identifies the font to
        # the system, we use a value transformer to show the user the display name
        fontSize = panelFont.pointSize()

        defaults = NSUserDefaultsController.sharedUserDefaultsController().values()
        defaults.setValue_forKey_(panelFont.fontName(), u"FontName")
        defaults.setValue_forKey_(fontSize, u"FontSize")

"""
Set up initial values for defaults:
Create dictionary with keys and values for WordOfTheDay, FontName,
FontSize, and FavoriteColor.  Mostly straightforward, but:

Store the fontName of the font as the default; the textfield displays
the font's displayName using a value transformer.

The color must be archived -- you can't store NSColors directly in NSUserDefaults.
"""

dictionary = {}
dictionary[u'WordOfTheDay'] = u'Today'
systemFont = NSFont.systemFontOfSize_(NSFont.systemFontSize())
dictionary[u"FontName"] = systemFont.fontName()
dictionary[u"FontSize"] = systemFont.pointSize()
archivedColor = NSArchiver.archivedDataWithRootObject_(NSColor.greenColor())
dictionary[u'FavoriteColor'] = archivedColor
NSUserDefaultsController.sharedUserDefaultsController().setInitialValues_(dictionary)

# Create and register font name value transformer
transformer = FontNameToDisplayNameTransformer.alloc().init()
NSValueTransformer.setValueTransformer_forName_(transformer, u'FontNameToDisplayNameTransformer')


text:
        <form id="theForm"></form>
        <button type="button" onclick="guslaboo.view.calculations.createFromTemplate(guslaboo.view.calculations.types.percentiles)">Add Calculation</button>

                <fieldset>
                    <legend>Percentile Calculation</legend>
                    Input Variable
                    <input type="text" value="" name="percentile-{generated-id}-input-variable"/>

                    Percentiles
                    <input type="text" value="" name="percentile-{generated-id}-percentiles"/>

                </fielset>


text:
Coffeelint plugin for Guard

## Installation

Add this line to your application's Gemfile:

    gem 'guard-coffeelint'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install guard-coffeelint

## Usage

1. Create and customize your config file:

  ```
  coffeelint --makeconfig > config/coffeelint.json
  ```

  By default guard-coffeelint will look in `config/coffeelint.json`,
  but you can override the location with `:config_file` in your Guardfile.

2. Add Coffeelint to your Guardfile:

  ```ruby
   # Lint CoffeeScript files on change
  guard :coffeelint do
    watch %r{^app/assets/javascripts/.*\.coffee$}
  end
  ```

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
import type {Node} from 'react';
import {ImageBackground, StyleSheet, Text, useColorScheme} from 'react-native';
import React from 'react';
import Colors from './Colors';
import HermesBadge from './HermesBadge';

const Header = (): Node => {
  const isDarkMode = useColorScheme() === 'dark';
  return (
    <ImageBackground
      accessibilityRole="image"
      testID="new-app-screen-header"
      source={require('./logo.png')}
      style={[
        styles.background,
        {
          backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
        },
      ]}
      imageStyle={styles.logo}>
      <HermesBadge />
      <Text
        style={[
          styles.text,
          {
            color: isDarkMode ? Colors.white : Colors.black,
          },
        ]}>
        Welcome to
        {'\n'}
        React Native
      </Text>
    </ImageBackground>
  );
};

const styles = StyleSheet.create({
  background: {
    paddingBottom: 40,
    paddingTop: 96,
    paddingHorizontal: 32,
  },
  logo: {
    opacity: 0.2,
    overflow: 'visible',
    resizeMode: 'cover',
    /*
     * These negative margins allow the image to be offset similarly across screen sizes and component sizes.
     *
     * The source logo.png image is 512x512px, so as such, these margins attempt to be relative to the
     * source image's size.
     */
    marginLeft: -128,
    marginBottom: -192,
  },
  text: {
    fontSize: 40,
    fontWeight: '700',
    textAlign: 'center',
  },
});

export default Header;


text:
package core

// http://www.awsarchitectureblog.com/2015/03/backoff.html

import (
	"math"
	mrand "math/rand"
	"sync"
	"time"
)

// DefaultInterval is used when a Backoff is initialised with a
// zero-value Interval.
var DefaultInterval = 5 * time.Minute

// DefaultMaxDuration is maximum amount of time that the backoff will
// delay for.
var DefaultMaxDuration = 6 * time.Hour

// A Backoff contains the information needed to intelligently backoff
// and retry operations using an exponential backoff algorithm. It may
// be initialised with all zero values and it will behave sanely.
type Backoff struct {
	// MaxDuration is the largest possible duration that can be
	// returned from a call to Duration.
	MaxDuration time.Duration

	// Interval controls the time step for backing off.
	Interval time.Duration

	// Jitter controls whether to use the "Full Jitter"
	// improvement to attempt to smooth out spikes in a high
	// contention scenario.
	Jitter bool

	tries int
	lock  *sync.Mutex // lock guards tries
}

func (b *Backoff) setup() {
	if b.Interval == 0 {
		b.Interval = DefaultInterval
	}

	if b.MaxDuration == 0 {
		b.MaxDuration = DefaultMaxDuration
	}

	if b.lock == nil {
		b.lock = new(sync.Mutex)
	}
}

// Duration returns a time.Duration appropriate for the backoff,
// incrementing the attempt counter.
func (b *Backoff) Duration() time.Duration {
	b.setup()
	b.lock.Lock()
	defer b.lock.Unlock()

	pow := 1 << uint(b.tries)

	// MaxInt16 is an arbitrary choice on an upper bound; the
	// implication is that every 16 tries, the counter resets.
	if pow > math.MaxInt16 {
		b.tries = 0
		pow = 1
	}

	t := time.Duration(pow)
	b.tries++
	t = b.Interval * t
	if t > b.MaxDuration {
		t = b.MaxDuration
	}

	if b.Jitter {
		t = time.Duration(mrand.Int63n(int64(t)))
	}

	return t
}


text:
class AddRpush < ActiveRecord::Migration
  def self.migrations
    [CreateRapnsNotifications, CreateRapnsFeedback,
     AddAlertIsJsonToRapnsNotifications, AddAppToRapns,
     CreateRapnsApps, AddGcm, AddWpns, AddAdm, RenameRapnsToRpush,
     AddFailAfterToRpushNotifications]
  end

  def self.up
    migrations.map(&:up)
  end

  def self.down
    migrations.reverse.each do |m|
      begin
        m.down
      rescue ActiveRecord::StatementInvalid => e
        p e
      end
    end
  end

  class CreateRapnsNotifications < ActiveRecord::Migration
    def self.up
      create_table :rapns_notifications do |t|
        t.integer   :badge,                 null: true
        t.string    :device_token,          null: false, limit: 64
        t.string    :sound,                 null: true,  default: "1.aiff"
        t.string    :alert,                 null: true
        t.text      :attributes_for_device, null: true
        t.integer   :expiry,                null: false, default: 1.day.to_i
        t.boolean   :delivered,             null: false, default: false
        t.timestamp :delivered_at,          null: true
        t.boolean   :failed,                null: false, default: false
        t.timestamp :failed_at,             null: true
        t.integer   :error_code,            null: true
        t.string    :error_description,     null: true
        t.timestamp :deliver_after,         null: true
        t.timestamps
      end

      add_index :rapns_notifications, [:delivered, :failed, :deliver_after], name: 'index_rapns_notifications_multi'
    end

    def self.down
      if index_name_exists?(:rapns_notifications, 'index_rapns_notifications_multi', true)
        remove_index :rapns_notifications, name: 'index_rapns_notifications_multi'
      end
      drop_table :rapns_notifications
    end
  end

  class CreateRapnsFeedback < ActiveRecord::Migration
    def self.up
      create_table :rapns_feedback do |t|
        t.string    :device_token,          null: false, limit: 64
        t.timestamp :failed_at,             null: false
        t.timestamps
      end

      add_index :rapns_feedback, :device_token
    end

    def self.down
      if index_name_exists?(:rapns_feedback, :index_rapns_feedback_on_device_token, true)
        remove_index :rapns_feedback, name: :index_rapns_feedback_on_device_token
      end
      drop_table :rapns_feedback
    end
  end

  class AddAlertIsJsonToRapnsNotifications < ActiveRecord::Migration
    def self.up
      add_column :rapns_notifications, :alert_is_json, :boolean, null: true, default: false
    end

    def self.down
      remove_column :rapns_notifications, :alert_is_json
    end
  end

  class AddAppToRapns < ActiveRecord::Migration
    def self.up
      add_column :rapns_notifications, :app, :string, null: true
      add_column :rapns_feedback, :app, :string, null: true
    end

    def self.down
      remove_column :rapns_notifications, :app
      remove_column :rapns_feedback, :app
    end
  end

  class CreateRapnsApps < ActiveRecord::Migration
    def self.up
      create_table :rapns_apps do |t|
        t.string    :key,             null: false
        t.string    :environment,     null: false
        t.text      :certificate,     null: false
        t.string    :password,        null: true
        t.integer   :connections,     null: false, default: 1
        t.timestamps
      end
    end

    def self.down
      drop_table :rapns_apps
    end
  end

  class AddGcm < ActiveRecord::Migration
    module Rapns
      class App < ActiveRecord::Base
        self.table_name = 'rapns_apps'
      end

      class Notification < ActiveRecord::Base
        belongs_to :app
        self.table_name = 'rapns_notifications'
      end
    end

    def self.up
      add_column :rapns_notifications, :type, :string, null: true
      add_column :rapns_apps, :type, :string, null: true

      AddGcm::Rapns::Notification.update_all type: 'Rapns::Apns::Notification'
      AddGcm::Rapns::App.update_all type: 'Rapns::Apns::App'

      change_column :rapns_notifications, :type, :string, null: false
      change_column :rapns_apps, :type, :string, null: false
      change_column :rapns_notifications, :device_token, :string, { null: true, limit: 64 }
      change_column :rapns_notifications, :expiry, :integer, { null: true, default: 1.day.to_i }
      change_column :rapns_apps, :environment, :string, null: true
      change_column :rapns_apps, :certificate, :text, null: true, default: nil

      change_column :rapns_notifications, :error_description, :text, null: true, default: nil
      change_column :rapns_notifications, :sound, :string, default: 'default'

      rename_column :rapns_notifications, :attributes_for_device, :data
      rename_column :rapns_apps, :key, :name

      add_column :rapns_apps, :auth_key, :string, null: true

      add_column :rapns_notifications, :collapse_key, :string, null: true
      add_column :rapns_notifications, :delay_while_idle, :boolean, null: false, default: false

      reg_ids_type = ActiveRecord::Base.connection.adapter_name.include?('Mysql') ? :mediumtext : :text
      add_column :rapns_notifications, :registration_ids, reg_ids_type, null: true
      add_column :rapns_notifications, :app_id, :integer, null: true
      add_column :rapns_notifications, :retries, :integer, null: true, default: 0

      AddGcm::Rapns::Notification.reset_column_information
      AddGcm::Rapns::App.reset_column_information

      AddGcm::Rapns::App.all.each do |app|
        AddGcm::Rapns::Notification.where(app: app.name).update_all(app_id: app.id)
      end

      change_column :rapns_notifications, :app_id, :integer, null: false
      remove_column :rapns_notifications, :app

      if index_name_exists?(:rapns_notifications, "index_rapns_notifications_multi", true)
        remove_index :rapns_notifications, name: "index_rapns_notifications_multi"
      elsif index_name_exists?(:rapns_notifications, "index_rapns_notifications_on_delivered_failed_deliver_after", false)
        remove_index :rapns_notifications, name: "index_rapns_notifications_on_delivered_failed_deliver_after"
      end
      add_index :rapns_notifications, [:app_id, :delivered, :failed, :deliver_after], name: "index_rapns_notifications_multi"
    end

    def self.down
      AddGcm::Rapns::Notification.where(type: 'Rapns::Gcm::Notification').delete_all

      remove_column :rapns_notifications, :type
      remove_column :rapns_apps, :type

      change_column :rapns_notifications, :device_token, :string, { null: false, limit: 64 }
      change_column :rapns_notifications, :expiry, :integer, { null: false, default: 1.day.to_i }
      change_column :rapns_apps, :environment, :string, null: false
      change_column :rapns_apps, :certificate, :text, null: false

      change_column :rapns_notifications, :error_description, :string, null: true, default: nil
      change_column :rapns_notifications, :sound, :string, default: '1.aiff'

      rename_column :rapns_notifications, :data, :attributes_for_device
      rename_column :rapns_apps, :name, :key

      remove_column :rapns_apps, :auth_key

      remove_column :rapns_notifications, :collapse_key
      remove_column :rapns_notifications, :delay_while_idle
      remove_column :rapns_notifications, :registration_ids
      remove_column :rapns_notifications, :retries

      add_column :rapns_notifications, :app, :string, null: true

      AddGcm::Rapns::Notification.reset_column_information
      AddGcm::Rapns::App.reset_column_information

      AddGcm::Rapns::App.all.each do |app|
        AddGcm::Rapns::Notification.where(app_id: app.id).update_all(app: app.key)
      end

      if index_name_exists?(:rapns_notifications, :index_rapns_notifications_multi, true)
          remove_index :rapns_notifications, name: :index_rapns_notifications_multi
      end

      remove_column :rapns_notifications, :app_id

      add_index :rapns_notifications, [:delivered, :failed, :deliver_after], name: :index_rapns_notifications_multi
    end
  end

  class AddWpns < ActiveRecord::Migration
    module Rapns
      class Notification < ActiveRecord::Base
        self.table_name = 'rapns_notifications'
      end
    end

    def self.up
      add_column :rapns_notifications, :uri, :string, null: true
    end

    def self.down
      AddWpns::Rapns::Notification.where(type: 'Rapns::Wpns::Notification').delete_all
      remove_column :rapns_notifications, :uri
    end
  end

  class AddAdm < ActiveRecord::Migration
    module Rapns
      class Notification < ActiveRecord::Base
        self.table_name = 'rapns_notifications'
      end
    end

    def self.up
      add_column :rapns_apps, :client_id, :string, null: true
      add_column :rapns_apps, :client_secret, :string, null: true
      add_column :rapns_apps, :access_token, :string, null: true
      add_column :rapns_apps, :access_token_expiration, :datetime, null: true
    end

    def self.down
      AddAdm::Rapns::Notification.where(type: 'Rapns::Adm::Notification').delete_all

      remove_column :rapns_apps, :client_id
      remove_column :rapns_apps, :client_secret
      remove_column :rapns_apps, :access_token
      remove_column :rapns_apps, :access_token_expiration
    end
  end

  class RenameRapnsToRpush < ActiveRecord::Migration
    module Rpush
      class App < ActiveRecord::Base
        self.table_name = 'rpush_apps'
      end

      class Notification < ActiveRecord::Base
        self.table_name = 'rpush_notifications'
      end
    end

    def self.update_type(model, from, to)
      model.where(type: from).update_all(type: to)
    end

    def self.up
      rename_table :rapns_notifications, :rpush_notifications
      rename_table :rapns_apps, :rpush_apps
      rename_table :rapns_feedback, :rpush_feedback

      if index_name_exists?(:rpush_notifications, :index_rapns_notifications_multi, true)
        rename_index :rpush_notifications, :index_rapns_notifications_multi, :index_rpush_notifications_multi
      end

      if index_name_exists?(:rpush_feedback, :index_rapns_feedback_on_device_token, true)
        rename_index :rpush_feedback, :index_rapns_feedback_on_device_token, :index_rpush_feedback_on_device_token
      end

      update_type(RenameRapnsToRpush::Rpush::Notification, 'Rapns::Apns::Notification', 'Rpush::Apns::Notification')
      update_type(RenameRapnsToRpush::Rpush::Notification, 'Rapns::Gcm::Notification', 'Rpush::Gcm::Notification')
      update_type(RenameRapnsToRpush::Rpush::Notification, 'Rapns::Adm::Notification', 'Rpush::Adm::Notification')
      update_type(RenameRapnsToRpush::Rpush::Notification, 'Rapns::Wpns::Notification', 'Rpush::Wpns::Notification')

      update_type(RenameRapnsToRpush::Rpush::App, 'Rapns::Apns::App', 'Rpush::Apns::App')
      update_type(RenameRapnsToRpush::Rpush::App, 'Rapns::Gcm::App', 'Rpush::Gcm::App')
      update_type(RenameRapnsToRpush::Rpush::App, 'Rapns::Adm::App', 'Rpush::Adm::App')
      update_type(RenameRapnsToRpush::Rpush::App, 'Rapns::Wpns::App', 'Rpush::Wpns::App')
    end

    def self.down
      update_type(RenameRapnsToRpush::Rpush::Notification, 'Rpush::Apns::Notification', 'Rapns::Apns::Notification')
      update_type(RenameRapnsToRpush::Rpush::Notification, 'Rpush::Gcm::Notification', 'Rapns::Gcm::Notification')
      update_type(RenameRapnsToRpush::Rpush::Notification, 'Rpush::Adm::Notification', 'Rapns::Adm::Notification')
      update_type(RenameRapnsToRpush::Rpush::Notification, 'Rpush::Wpns::Notification', 'Rapns::Wpns::Notification')

      update_type(RenameRapnsToRpush::Rpush::App, 'Rpush::Apns::App', 'Rapns::Apns::App')
      update_type(RenameRapnsToRpush::Rpush::App, 'Rpush::Gcm::App', 'Rapns::Gcm::App')
      update_type(RenameRapnsToRpush::Rpush::App, 'Rpush::Adm::App', 'Rapns::Adm::App')
      update_type(RenameRapnsToRpush::Rpush::App, 'Rpush::Wpns::App', 'Rapns::Wpns::App')

      if index_name_exists?(:rpush_notifications, :index_rpush_notifications_multi, true)
        rename_index :rpush_notifications, :index_rpush_notifications_multi, :index_rapns_notifications_multi
      end

      if index_name_exists?(:rpush_feedback, :index_rpush_feedback_on_device_token, true)
        rename_index :rpush_feedback, :index_rpush_feedback_on_device_token, :index_rapns_feedback_on_device_token
      end

      rename_table :rpush_notifications, :rapns_notifications
      rename_table :rpush_apps, :rapns_apps
      rename_table :rpush_feedback, :rapns_feedback
    end
  end

  class AddFailAfterToRpushNotifications < ActiveRecord::Migration
    def self.up
      add_column :rpush_notifications, :fail_after, :timestamp, null: true
    end

    def self.down
      remove_column :rpush_notifications, :fail_after
    end
  end
end


text:
import { isArray } from './is';

export function addToArray(array, value) {
  const index = array.indexOf(value);

  if (index === -1) {
    array.push(value);
  }
}

export function arrayContains(array, value) {
  for (let i = 0, c = array.length; i < c; i += 1) {
    if (array[i] === value) {
      return true;
    }
  }

  return false;
}

export function arrayContentsMatch(a, b) {
  let i;

  if (!isArray(a) || !isArray(b)) {
    return false;
  }

  if (a.length !== b.length) {
    return false;
  }

  i = a.length;
  while (i--) {
    if (a[i] !== b[i]) {
      return false;
    }
  }

  return true;
}

export function ensureArray(x) {
  if (typeof x === 'string') {
    return [x];
  }

  if (x === undefined) {
    return [];
  }

  return x;
}

export function lastItem(array) {
  return array[array.length - 1];
}

export function removeFromArray(array, member) {
  if (!array) {
    return;
  }

  const index = array.indexOf(member);

  if (index !== -1) {
    array.splice(index, 1);
  }
}

export function toArray(arrayLike) {
  const array = [];
  let i = arrayLike.length;
  while (i--) {
    array[i] = arrayLike[i];
  }

  return array;
}

export function findByKeyValue(array, key, value) {
  return array.filter(obj => {
    return obj[key] === value;
  });
}


text:
package widgets.edit;

import grid.NDGridBlock;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.text.Font;

public class CurrentBlockInfoWgt {
    // Display text for nil(Unused) block.
    public static String NIL_STR = "-------";

    // Arrangement node.
    private HBox box;
    // Labels.
    private final Label curBlockLabel;
    private Label curBlockValLabel;

    public CurrentBlockInfoWgt() {
        // Labels:
        this.curBlockLabel = new Label("Block:");
        this.curBlockLabel.setFont(new Font(10) );
        this.curBlockValLabel = new Label();
        this.curBlockValLabel.setFont(new Font(12) );

        this.box = new HBox();
        this.box.setSpacing( 5 );
        this.box.setAlignment( Pos.CENTER_LEFT);
        this.box.getChildren().addAll(this.curBlockLabel, this.curBlockValLabel);
    }

    public HBox build() {
        return this.box;
    }

    // ---------------------
    // Update Info

    // Set text as "#0f33d0" for non-nil block.
    public void update(NDGridBlock block) {
        String str;
        if (block.isNil()) {
            str = NIL_STR;
        }else{
            str = block.getColorHex();
        }

        this.curBlockValLabel.setText( str );
        // Onlu change text color is not a good idea, need to change background color too.
//        this.curBlockValLabel.setTextFill( block.getColor() );
    }
}


text:
package autocert

import (
	"bytes"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/tls"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/pem"
	"fmt"
	"html/template"
	"math/big"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"golang.org/x/crypto/acme/internal/acme"
	"golang.org/x/net/context"
)

var discoTmpl = template.Must(template.New("disco").Parse(`{
	"new-reg": "{{.}}/new-reg",
	"new-authz": "{{.}}/new-authz",
	"new-cert": "{{.}}/new-cert"
}`))

var authzTmpl = template.Must(template.New("authz").Parse(`{
	"status": "pending",
	"challenges": [
		{
			"uri": "{{.}}/challenge/1",
			"type": "tls-sni-01",
			"token": "token-01"
		},
		{
			"uri": "{{.}}/challenge/2",
			"type": "tls-sni-02",
			"token": "token-02"
		}
	]
}`))

func dummyCert(san ...string) ([]byte, error) {
	// use EC key to run faster on 386
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, err
	}
	t := &x509.Certificate{
		SerialNumber:          big.NewInt(1),
		NotBefore:             time.Now(),
		NotAfter:              time.Now().Add(24 * time.Hour),
		BasicConstraintsValid: true,
		KeyUsage:              x509.KeyUsageKeyEncipherment,
		DNSNames:              san,
	}
	return x509.CreateCertificate(rand.Reader, t, t, &key.PublicKey, key)
}

func TestGetCertificate(t *testing.T) {
	const domain = "example.org"
	man := &Manager{Prompt: AcceptTOS}

	// echo token-02 | shasum -a 256
	// then divide result in 2 parts separated by dot
	tokenCertName := "4e8eb87631187e9ff2153b56b13a4dec.13a35d002e485d60ff37354b32f665d9.token.acme.invalid"
	verifyTokenCert := func() {
		hello := &tls.ClientHelloInfo{ServerName: tokenCertName}
		_, err := man.GetCertificate(hello)
		if err != nil {
			t.Errorf("verifyTokenCert: GetCertificate(%q): %v", tokenCertName, err)
			return
		}
	}

	// ACME CA server stub
	var ca *httptest.Server
	ca = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("replay-nonce", "nonce")
		switch r.URL.Path {
		// discovery
		case "/":
			if err := discoTmpl.Execute(w, ca.URL); err != nil {
				t.Fatalf("discoTmpl: %v", err)
			}
		// client key registration
		case "/new-reg":
			w.Write([]byte("{}"))
		// domain authorization
		case "/new-authz":
			w.Header().Set("location", ca.URL+"/authz/1")
			w.WriteHeader(http.StatusCreated)
			if err := authzTmpl.Execute(w, ca.URL); err != nil {
				t.Fatalf("authzTmpl: %v", err)
			}
		// accept tls-sni-02 challenge
		case "/challenge/2":
			verifyTokenCert()
			w.Write([]byte("{}"))
		// authorization status
		case "/authz/1":
			w.Write([]byte(`{"status": "valid"}`))
		// cert request
		case "/new-cert":
			der, err := dummyCert(domain)
			if err != nil {
				t.Fatalf("new-cert: dummyCert: %v", err)
			}
			chainUp := fmt.Sprintf("<%s/ca-cert>; rel=up", ca.URL)
			w.Header().Set("link", chainUp)
			w.WriteHeader(http.StatusCreated)
			w.Write(der)
		// CA chain cert
		case "/ca-cert":
			der, err := dummyCert("ca")
			if err != nil {
				t.Fatalf("ca-cert: dummyCert: %v", err)
			}
			w.Write(der)
		default:
			t.Errorf("unrecognized r.URL.Path: %s", r.URL.Path)
		}
	}))
	defer ca.Close()

	// use EC key to run faster on 386
	key, kerr := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if kerr != nil {
		t.Fatal(kerr)
	}
	man.Client = &acme.Client{
		Key:          key,
		DirectoryURL: ca.URL,
	}

	// simulate tls.Config.GetCertificate
	var (
		tlscert *tls.Certificate
		err     error
		done    = make(chan struct{})
	)
	go func() {
		hello := &tls.ClientHelloInfo{ServerName: domain}
		tlscert, err = man.GetCertificate(hello)
		close(done)
	}()
	select {
	case <-time.After(time.Minute):
		t.Fatal("man.GetCertificate took too long to return")
	case <-done:
	}
	if err != nil {
		t.Fatalf("man.GetCertificate: %v", err)
	}

	// verify the tlscert is the same we responded with from the CA stub
	if len(tlscert.Certificate) == 0 {
		t.Fatal("len(tlscert.Certificate) is 0")
	}
	cert, err := x509.ParseCertificate(tlscert.Certificate[0])
	if err != nil {
		t.Fatalf("x509.ParseCertificate: %v", err)
	}
	if len(cert.DNSNames) == 0 || cert.DNSNames[0] != domain {
		t.Errorf("cert.DNSNames = %v; want %q", cert.DNSNames, domain)
	}

	// make sure token cert was removed
	done = make(chan struct{})
	go func() {
		for {
			hello := &tls.ClientHelloInfo{ServerName: tokenCertName}
			if _, err := man.GetCertificate(hello); err != nil {
				break
			}
			time.Sleep(100 * time.Millisecond)
		}
		close(done)
	}()
	select {
	case <-time.After(5 * time.Second):
		t.Error("token cert was not removed")
	case <-done:
	}
}

type memCache map[string][]byte

func (m memCache) Get(ctx context.Context, key string) ([]byte, error) {
	v, ok := m[key]
	if !ok {
		return nil, ErrCacheMiss
	}
	return v, nil
}

func (m memCache) Put(ctx context.Context, key string, data []byte) error {
	m[key] = data
	return nil
}

func (m memCache) Delete(ctx context.Context, key string) error {
	delete(m, key)
	return nil
}

func TestCache(t *testing.T) {
	privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Fatal(err)
	}
	tmpl := &x509.Certificate{
		SerialNumber: big.NewInt(1),
		Subject:      pkix.Name{CommonName: "example.org"},
		NotAfter:     time.Now().Add(time.Hour),
	}
	pub, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &privKey.PublicKey, privKey)
	if err != nil {
		t.Fatal(err)
	}
	tlscert := &tls.Certificate{
		Certificate: [][]byte{pub},
		PrivateKey:  privKey,
	}

	cache := make(memCache)
	man := Manager{Cache: cache}
	if err := man.cachePut("example.org", tlscert); err != nil {
		t.Fatalf("man.cachePut: %v", err)
	}
	res, err := man.cacheGet("example.org")
	if err != nil {
		t.Fatalf("man.cacheGet: %v", err)
	}
	if res == nil {
		t.Fatal("res is nil")
	}

	priv, err := x509.MarshalECPrivateKey(privKey)
	if err != nil {
		t.Fatalf("MarshalECPrivateKey: %v", err)
	}
	dummy, err := dummyCert("dummy")
	if err != nil {
		t.Fatalf("dummyCert: %v", err)
	}
	tt := []struct {
		key      string
		prv, pub []byte
	}{
		{"dummy", priv, dummy},
		{"bad1", priv, []byte{1}},
		{"bad2", []byte{1}, pub},
	}
	for i, test := range tt {
		var buf bytes.Buffer
		pb := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: test.prv}
		if err := pem.Encode(&buf, pb); err != nil {
			t.Errorf("%d: pem.Encode: %v", i, err)
		}
		pb = &pem.Block{Type: "CERTIFICATE", Bytes: test.pub}
		if err := pem.Encode(&buf, pb); err != nil {
			t.Errorf("%d: pem.Encode: %v", i, err)
		}

		cache.Put(nil, test.key, buf.Bytes())
		if _, err := man.cacheGet(test.key); err == nil {
			t.Errorf("%d: err is nil", i)
		}
	}
}

func TestHostWhitelist(t *testing.T) {
	policy := HostWhitelist("example.com", "example.org", "*.example.net")
	tt := []struct {
		host  string
		allow bool
	}{
		{"example.com", true},
		{"example.org", true},
		{"one.example.com", false},
		{"two.example.org", false},
		{"three.example.net", false},
		{"dummy", false},
	}
	for i, test := range tt {
		err := policy(nil, test.host)
		if err != nil && test.allow {
			t.Errorf("%d: policy(%q): %v; want nil", i, test.host, err)
		}
		if err == nil && !test.allow {
			t.Errorf("%d: policy(%q): nil; want an error", i, test.host)
		}
	}
}


text:
<?php
namespace Helmich\ProductsApiAdvanced\Normalizer\Decorator;

use Helmich\RestTools\Rest\Normalizer\NormalizerInterface;
use TYPO3\Flow\Mvc\Routing\UriBuilder;

class ProductHypermediaDecorator implements NormalizerInterface {

	/** @var UriBuilder */
	protected $uriBuilder;

	/** @var NormalizerInterface */
	protected $actual;

	public function __construct(NormalizerInterface $actual, UriBuilder $uriBuilder) {
		$this->uriBuilder = $uriBuilder;
		$this->actual     = $actual;
	}

	public function objectToScalar($object) {
		$scalar          = $this->actual->objectToScalar($object);
		$scalar['href']  = $this->uriBuilder->reset()->uriFor('show', ['product' => $object], 'Product');
		$scalar['links'] = [
			[
				'rel'  => 'inventoryChanges',
				'href' => $this->uriBuilder->reset()->uriFor('list', ['product' => $object], 'InventoryChange')
			]
		];

		return $scalar;
	}
}


text:
MCSMTableViewDataSource
=======================