import fs from 'fs'
import awaitFs from 'await-fs'


// List downloaded files
async function getFiles(req, res) {
    const tournament = req.query.tournament
    const dirContent = await awaitFs.readdir('swisstennis_files')
    const fileList = dirContent.filter(filename => {
      return tournament ? filename.includes(tournament) : true
    }).map(filename => {
      const stats = fs.statSync(`swisstennis_files/${filename}`)
      return { filename, size: stats.size, mtime: stats.mtime }
    })
    return res.json(fileList)
  }
  
 async function deleteFile (req, res) {
    try {
      const { filename } = req.body
      fs.unlink(`swisstennis_files/${filename}`, (error) => {
        if (error) throw error
        res.json({ msg: `successfully deleted swisstennis_files/${filename}.` })
      })
    } catch (error) {
      return res.status(400).json({ msg: error.toString() })
    }
  }

  export default { getFiles, deleteFile }