const express = require('express'),
  passport = require('passport'),
  Strategy = require('passport-local').Strategy,
  crypto = require('crypto'),
  fs = require('fs'),
  config = require('./config'),
  rfs = require('rotating-file-stream'),
  accessLogStream = rfs('access.log', {
    interval: '1d', // rotate daily
    path: __dirname + '/log'
  }),
  upload = require('multer')({
    dest: 'uploads/',
    limits: {
      fileSize: 5 * 1024 * 1024 // 5Mb
    }
  }),
  tika = require('tika'),
  flash = require('connect-flash'),
  promisify = require("es6-promisify").promisify,
  nodemailer = require('nodemailer'),
  transporter = nodemailer.createTransport({
    host: config.mailserver,
    port: config.mailport,
    secure: config.mailsecure,
    auth: {
      user: config.mailuser,
      pass: config.mailpass
    }
  }),
  { Client: Client6 } = require('es6'),
  client6 = new Client6({
    node: config.indexhost,
    auth: {
      username: config.indexuser,
      password: config.indexpass
    }
  }),
  exiftool = require('node-exiftool');

// Initialize elastic
require('./lib/elastic')(config, client6)

// Server
const app = express(),
  server = app.disable('x-powered-by').listen(config.port, () => {
    console.log(`Listening on ${server.address().address}:${server.address().port}`)
  })

app.set('trust proxy', 1)

app.set('views', __dirname + '/views')
app.set('view engine', 'ejs')

// Middleware
app.use(require('morgan')('combined', { stream: accessLogStream }))
app.use(require('body-parser').json())
app.use(require('body-parser').urlencoded({ extended: false }))
app.use(require('express-session')({ secret: 'keyboard hat', resave: false, saveUninitialized: true }))
app.use(flash())

// Auth
require('./lib/passport')(passport, Strategy, crypto, config, client6)
app.use(passport.initialize())
app.use(passport.session({ cookie: { maxAge: 43200 } })) // 12H

// Routes
app.use('/', require('./lib/index')(express.Router(), passport, config, client6, upload, fs, tika, promisify, crypto, transporter))
app.use('/user', require('connect-ensure-login').ensureLoggedIn('/login'), require('./lib/user')(express.Router(), config, client6, upload, fs, tika, promisify, crypto, exiftool))

// Resources
app.use('/css', express.static(__dirname + '/public/css'))
app.use('/js', express.static(__dirname + '/public/js'))

// Errors
app.use((err, req, res, next) => {
  res.status(500)
  return res.render('error', { error: err.message })
})