import express from 'express'
import bhttp from 'bhttp'

import tournament from './routes/tournament'
import calendar from './routes/calendar'
import playerList from './routes/playerList'
import draw from './routes/draw'
import files from './routes/files'

import { configDb } from '../api'

// Create the router
export const swisstennis = express.Router()

// Use this variable for the session
export const session = bhttp.session()

async function checkLogin() {
  const myTournamentsPage = await session.get(
    'https://comp.swisstennis.ch/advantage/servlet/MyTournamentList?Lang=D'
  )
  const strMyTournamentsPage = myTournamentsPage.body.toString()
  return strMyTournamentsPage.includes('Login-Zone')
    ? null
    : strMyTournamentsPage
}

/*
 * Define the Routes
 */

// Login
swisstennis.post('/login', async (req, res) => {
  try {
    const currentState = await checkLogin()
    if (currentState) {
      return res.json({ msg: 'Already logged in!' })
    }
    const username = req.body.username || configDb.tournament.value
    const password = req.body.password || configDb.tournamentPW.value
    console.log('Swisstennis login', username, password)

    // return, if username or password are missing
    if (!username || !password) {
      throw Error('Parameters username and password are required')
    }

    // assemble the login data
    const loginData = {
      Lang: 'D',
      id: username,
      pwd: password,
      Tournament: '',
    }
    const loginPage = await session.post(
      'https://comp.swisstennis.ch/advantage/servlet/Login',
      loginData
    )
    const strLoginPage = loginPage.body.toString()
    if (strLoginPage.includes('Zugriff verweigert')) {
      throw Error('Access denied!')
    }
  } catch (error) {
    return res.status(400).json({ msg: error.toString() })
  }
  res.json({ msg: 'Logged in successfully.' })
})

// Tournament actions
swisstennis.get('/tournaments', tournament.getTournaments)
swisstennis.get('/tournament/draws', tournament.getTournamentDraws)

// Calendar actions
swisstennis.get('/calendars', calendar.getCalendars)
swisstennis.get('/calendar', calendar.getCalendar)
swisstennis.get('/calendar/download', calendar.downloadCalendar)
swisstennis.get('/calendar/parse/:filename', calendar.parseCalendar)
swisstennis.delete('/calendar/:calendarId', calendar.deleteCalendar)

// PlayerList actions
swisstennis.get('/playerlist/download', playerList.downloadPlayerList)
swisstennis.get('/playerlists', playerList.getPlayerLists)
swisstennis.get('/playerlist', playerList.getPlayerList)
swisstennis.get('/playerlist/parse/:filename', playerList.parsePlayerList)
swisstennis.delete('/playerlist/:playerlistId', playerList.deletePlayerList)

// Draw actions
swisstennis.get('/draws', draw.getDraws)
swisstennis.get('/draw', draw.getDraw)
swisstennis.get('/draw/download/:drawId', draw.downloadDraw)
swisstennis.get('/draw/parse/:filename', draw.parseDraw)
swisstennis.delete('/draw/:drawId', draw.deleteDraw)

// File actions
swisstennis.get('/files', files.getFiles)
swisstennis.delete('/file', files.deleteFile)

export default swisstennis
