const knex = require('../../database/knex.config')()

function gamescontroller() {
  return {
    async index(req, res) {
      const data = await knex('games').orderBy('id', 'desc')
      res.render('game', { data: data })
    },

    async newGameAdd(req, res) {
      await knex('games').insert({
        name: req.body.name,
        category: req.body.category,
        description: req.body.description,
        description_two: req.body.description_two,
        description_three: req.body.description_three,
        description_four: req.body.description_four,
        thumbnail: "",
        bannerImage: `/upload/${req.files.bannerImage[0].filename}`,
        logo: `/upload/${req.files.logo[0].filename}`,
        link: req.body.link,
      })
      return res.redirect('/admin/games')
    },

    async gameEdit(req, res) {
      if (req.files) {

        if (req.files.bannerImage) {
          await knex('games').update({
            bannerImage: `/upload/${req.files.bannerImage[0].filename}`,
          }).where('id', parseInt(req.body.id))
        }
        if (req.files.logo) {
          await knex('games').update({
            logo: `/upload/${req.files.logo[0].filename}`,
          }).where('id', parseInt(req.body.id))
        }
      }
      await knex('games').update({
        name: req.body.name,
        category: req.body.category,
        description: req.body.description,
        description_two: req.body.description_two,
        description_three: req.body.description_three,
        description_four: req.body.description_four,
        link: req.body.link,
      }).where('id', parseInt(req.body.id))
      return res.redirect('/admin/games')
    },


    async gameDelete(req, res) {
      await knex('games').where('id', parseInt(req.params.id)).delete()
      return res.redirect('/admin/games')
    },


    async gameLike(req, res) {
      const data = await knex('games').where('id', parseInt(req.params.id)).first()
      if (data) {
        const a = parseInt(data.like) + 1
        await knex('games').update({
          like: a
        }).where('id', parseInt(data.id))
        return res.json({
          res: true,
          message: 'Like a Game!'
        })

      } else {
        return res.json({
          res: false,
          message: 'Somthing went to wrong!'
        })
      }
    },

    async popularGameData(req, res) {
      const data = await knex('games').orderBy('like', 'desc').limit(10)
      return res.json({
        res: true,
        message: 'success',
        data: data
      })
    }
  }
}

module.exports = gamescontroller;