const path = require('path')
const profile = require('./models/profile')

exports.init = (app, done) => {

  function login(req, res) {
    res.sendFile(path.join(__dirname, '..', 'client', 'login.html'))
  }

  function authorizeBrowser(req, res) {
    app.logger.debug(req.body)

    // do some checking

    res.cookie('email', req.body.email)
    res.redirect('/')
  }

  function is_logged_in(req, res, next) {
    const status = req.cookies.email ? true : false
    status ? next() : res.redirect('/login')
  }

  function logout(req, res) {
    ['email', 'io'].forEach(cookie => res.clearCookie(cookie))
    res.redirect('/login')
  }

  // auth routes
  app.get('/login', login)
  app.post('/login', authorizeBrowser)
  app.get('/logout', logout)

  // api-driven routes
  // app.get('/api/authorize', authorizeAPI)
  app.get('/api/profiles', is_logged_in, profile.getProfile)
  app.get('/api/settings', is_logged_in, profile.getSettings)
  app.get('/api/messages/:roomID', is_logged_in, app.db.getRoomMessages)
  app.post('/api/messages', is_logged_in, app.db.receiveMessage)
  app.get('/api/search', is_logged_in, app.db.searchMessages)

  // serve react application
  app.get('/', is_logged_in, (req, res) => {
    res.sendFile(path.join(__dirname, '..', 'client', 'index.html'))
  })

  app.logger.info('Initialized routes')
  done()
}

@@ -65,16 +65,57 @@
 rofile')
+%0Aconst scrambler = require('./scrambler')
 %0A%0Aexport
@@ -423,55 +423,461 @@
 ion 
-is_logged_in(req, res, next) %7B%0A    const status
+authorizeAPI(req, res) %7B%0A    const credentials = req.headers.auth ? req.headers.auth : req.cookies.email%0A    res.send(%7B%0A      auth: scrambler.encrypt(credentials)%0A    %7D)%0A  %7D%0A%0A  function is_logged_in(req, res, next) %7B%0A    try %7B%0A      const apiLogin = scrambler.decrypt(req.headers.auth) ? true : false%0A      apiLogin ? next() : res.redirect('/login')%0A    %7D catch (e) %7B%0A      // scrambler could not decrypt authorization header%0A      const browserLoggedIn
  = r
@@ -916,14 +916,25 @@
     
-status
+  browserLoggedIn
  ? n
@@ -960,24 +960,30 @@
 t('/login')%0A
+    %7D%0A
   %7D%0A%0A  funct
@@ -1237,19 +1237,16 @@
 routes%0A 
- //
  app.get

refactor middleware to accomodate api and browser access