var router = require('express').Router();
const server = require('../../server.js')
const route_name = "/services/services"
const permissions_manager = require("../../utils/permissions-manager")
const config = require('../../config.json')
server.logger(" [INFO] /api" + route_name + " route loaded !")

router.get('', function (req, res) {
  ipInfo = server.ip(req);
  var forwardedIpsStr = req.header('x-forwarded-for');
  var IP = '';

  if (forwardedIpsStr) {
    IP = forwardedIps = forwardedIpsStr.split(',')[0];
  }
  server.logger(' [DEBUG] GET /api' + route_name + ' from ' + IP + ` with uuid ${req.query.uuid}`)
  var sql = `SELECT token FROM users WHERE uuid = '${req.query.uuid}'`;
  server.con.query(sql, function (err, result) {
    if (err) { server.logger(" [ERROR] Database error\n  " + err) };
    if (result.length == 0) {
      return res.json({ 'error': true, 'code': 404 })
    } else {
      if (result[0].token === req.query.token) {
        permissions_manager.has_permission(req.query.uuid, "LISTSERVICES").then(function (result) {
          if (result) {
            var sql = `SELECT * FROM services;`;
            server.con.query(sql, function (err, result) {
              if (err) { server.logger(" [ERROR] Database error\n  " + err) };
              server.fetch(config.pterodactyl_url + "/api/application/servers", {
                "method": "GET",
                "headers": {
                  "Accept": "application/json",
                  "Content-Type": "application/json",
                  "Authorization": `Bearer ${config.pterodactyl_api_key}`,
                }
              }).then(response => {
                return response.json()
              }).then(data => {
                var servers = []
                for (let i = 0; i < data.data.length; i++) {
                  for (let ii = 0; ii < result.length; ii++) {
                    const configuration = JSON.parse(result[ii].configuration)
                    if (configuration.id == data.data[i].attributes.id) {
                      servers.push({
                        'ptero_i': i,
                        'service_i': ii
                      })
                    }
                  }
                }
                var services = []
                for (let i = 0; i < result.length; i++) {
                  if (data.data[servers[i].ptero_i].attributes.suspended == true) {
                    statut = "suspended"
                  } else if (data.data[servers[i].ptero_i].attributes.container.installed == false) {
                    statut = "installing"
                  } else {
                    statut = "active"
                  }
                  services.push({
                    "id": result[i].id,
                    "uuid": result[i].uuid,
                    "name": result[i].name,
                    "product_id": result[i].product_id,
                    "price": result[i].price,
                    "category": result[i].category,
                    "statut": statut
                  })
                }
                return res.json({ 'error': false, 'data': services })
              }).catch(err => { server.logger(" [ERROR] Pterodactyl API error : " + err); return res.json({ "error": true, "code": 503, "msg": "Pterodactyl API error : " + err }) })
            });
          } else {
            var sql = `SELECT * FROM services WHERE uuid = '${req.query.uuid}';`;
            server.con.query(sql, function (err, result) {
              if (err) { server.logger(" [ERROR] Database error\n  " + err) };
              server.fetch(config.pterodactyl_url + "/api/application/servers", {
                "method": "GET",
                "headers": {
                  "Accept": "application/json",
                  "Content-Type": "application/json",
                  "Authorization": `Bearer ${config.pterodactyl_api_key}`,
                }
              }).then(response => {
                return response.json()
              }).then(data => {
                var servers = []
                for (let i = 0; i < data.data.length; i++) {
                  for (let ii = 0; ii < result.length; ii++) {
                    const configuration = JSON.parse(result[ii].configuration)
                    if (configuration.id == data.data[i].attributes.id) {
                      servers.push({
                        'ptero_i': i,
                        'service_i': ii
                      })
                    }
                  }
                }
                console.log(servers)
              }).catch(err => { server.logger(" [ERROR] Pterodactyl API error : " + err); return req.json({ "error": true, "code": 503, "msg": "Pterodactyl API error : " + err }) })
              return res.json({ 'error': false, 'data': result })
            });
          }
        })
      } else {
        return res.json({ 'error': true, 'code': 403 })
      }
    }
  });
})

module.exports = router;