import express from 'express'
import cors from 'cors'
import bodyParser from 'body-parser'
import mongoose from 'mongoose'
import sockjs from 'sockjs'
import configFile from './config/database'

import users from './routes/users'
import swisstennis from './swisstennis'
import sztm from './routes/sztm'
import config from './routes/config'
import { listConfigs } from './routes/config'
import download from './routes/download'
import sms from './routes/sms'

import { authenticate, verify } from './routes/authenticate'
import errorHandler from './middleware/apiErrorHandler'

mongoose.connect(configFile.database)

export const configDb = {}
listConfigs().then(
  (results) => {
    results.forEach((result) => {
      configDb[result.key] = {
        value: result.value,
        description: result.description,
      }
    })
  },
  (error) => {
    console.log(error)
  }
)

const socketServer = sockjs.createServer({ disable_cors: true })
socketServer.on('connection', (connection) => {
  console.log('Connection established', connection.id)
  connection.on('close', () => {
    console.log('Connection closed', connection.id)
  })
  connection.on('data', (message) => {
    connection.write('Connection message', connection.id, message)
  })
})

const port = process.env.PORT || 3002
const app = express()

socketServer.installHandlers(app, { prefix: '/socket' })
app.use(cors())

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json({ limit: '50mb' }))

app.get('/', (req, res) => {
  res.send(`Express API`)
})

// Paths outside the protected zone
app.use('/authenticate', authenticate)
app.use('/download', download)

// Paths inside the protected zone
const apiRoutes = express.Router()
apiRoutes.use('/users', users)
apiRoutes.use('/swisstennis', swisstennis)
apiRoutes.use('/sztm', sztm)
apiRoutes.use('/config', config)
apiRoutes.use('/sms', sms)

// Use verify to protect zone
app.use('/api', verify)
app.use('/api', apiRoutes)

// Catch errors in the error handler
app.use(errorHandler)

app.listen(port)
console.log(`Server running on port ${port}.`)
