import { session } from '../index'


// Overview of tournaments
async function getTournaments (req, res) {
    try {
      const myTournamentsPage = await session.get('https://comp.swisstennis.ch/advantage/servlet/MyTournamentList?Lang=D')
      const strMyTournamentsPage = myTournamentsPage.body.toString()
      if (strMyTournamentsPage.includes('Login-Zone')) {
        throw Error('Not logged in!')
      }
  
      const tournamentRegexp = /<a href=".*ProtectedDisplayTournament.*tournament=Id(\d+)">([^<]+)<\/a>/gm
  
      const tournaments = {}
      let match
      
      do {
        match = tournamentRegexp.exec(strMyTournamentsPage)
        if (match) {
          tournaments[match[1]] = match[2]
        }
      } while (match)
      res.json({ tournaments })
    } catch (error) {
      return res.status(400).json({ msg: error.toString() })
    }
  }
  
  // Draws of a tournament
  async function getTournamentDraws (req, res) {
    try {
      const tournament = req.params.tournament || config.tournamentId
      if (!tournament) {
        throw Error('No tournament given.')
      }
      
      let match
      const draws = {}
      const tournamentPage = await session.get(`https://comp.swisstennis.ch/advantage/servlet/ProtectedDisplayTournament?Lang=D&tournament=Id${tournament}`)
      const strTournamentPage = tournamentPage.body.toString()
      if (strTournamentPage.includes('Login-Zone')) {
        throw Error('Not logged in.')
      }
      const drawRegexp = /<a (?:class="text" )?href=".*DisplayEvent.*eventId=(\d+).*">([^<]+)<\/a>/gm
      
      do {
        match = drawRegexp.exec(strTournamentPage)
        if (match) {
          draws[match[1]] = match[2]
        }
      } while (match)
      return res.json({ draws })
    } catch (error) {
      return res.status(400).json({ msg: error.toString() })
    }
  }

  export default { getTournaments, getTournamentDraws }