import express from 'express'
import bodyParser from 'body-parser'
import mongoose from 'mongoose'
import bcrypt from 'bcrypt'
import jwt from 'jsonwebtoken'
import bhttp from 'bhttp'

import config from './config/database'
import User from './models/user'

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

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

app.get('/', (req, res) => {
  res.send(`Express API at http://localhost:${port}/api`)
})

mongoose.connect(config.database)
const apiRoutes = express.Router()

apiRoutes.post('/login', (req, res) => {
  const { username, password } = req.body
  if (!username || !password) {
    res.status(400).json({ success: false, msg: 'Parameters name and password are required' })
    return
  }

  User.findOne({ name: username }, (err, user) => {
    if (err) {
      res.status(400).json({ success: false, msg: err })
      return
    }
    if (!user) {
      res.status(400).json({ success: false, msg: 'Authentication failed. User not found.' })
      return
    }
    console.log(password, user)
    if (!bcrypt.compareSync(password, user.password)) {
      res.status(400).json({ success: false, msg: 'Authentication failed. Wrong password' })
    } else {
      const token = jwt.sign({
        exp: Math.floor(Date.now() / 1000) + 24*60*60,
        data: user
      }, "bugu")
      res.json({ success: true, token })
    }
  })
})

const swisstennis = express.Router()
swisstennis.post('/login', async (req, res) => {
  const { username, tournament, password } = req.body
  const session = bhttp.session()
  if (!username || !password) {
    res.status(400).json({ success: false, msg: 'Parameters username and password are required' })
    return
  }
  const loginData = {
    Lang: 'D',
    id: username,
    pwd: password,
    Tournament: ''
  }
  try {
    console.log('attempting to fetch login page.')
    const reqPage = await session.get('https://comp.swisstennis.ch/advantage/servlet/MyTournamentList?Lang=D')
    console.log('successfully fetched login page.')
  } catch (error) {
    console.log('Error fetching login page.', error)
    res.status(400).json({
      msg: error
    })
    return
  }
  try {
    console.log('attempting to login.', loginData)
    const loginPage = await session.post('https://comp.swisstennis.ch/advantage/servlet/Login', loginData)
    const dec = loginPage.body.toString()
    console.log('received a page.')
    if (dec.includes('Zugriff verweigert')) {
      console.log('failed to log in')
      res.status(400).json({
        msg: dec
      })
      return
    }
  } catch (error) {
    console.log('Error logging in.', error)
    res.status(400).json({
      msg: error
    })
    return
  }
  try {
    console.log('attempting to fetch my tournaments.')
    const myTournamentsPage = await session.get('https://comp.swisstennis.ch/advantage/servlet/MyTournamentList?Lang=D')
    const mdec = myTournamentsPage.body.toString()
    let match
    const matches = {}
    const regexp = /<a href=".*ProtectedDisplayTournament.*tournament=Id(\d+)">([^<]+)<\/a>/gm
    
    do {
      match = regexp.exec(mdec)
      console.log(match)
      if (match) {
        matches[match[1]] = match[2]
      }
    } while (match)
    res.json({
      matches
    })
  } catch (error) {
    console.log('Error fetching tournaments.')
    res.status(400).json({
      msg: error
    })
    return
  }  
})

apiRoutes.use('/swisstennis', swisstennis)

app.use('/api', apiRoutes)

app.listen(port)
console.log('Server running.')
