var express = require('express');
var router = express.Router();
var path = require("path")
var auth = require("../../modules/sub-auth")
var log = require("loguix")
var uuid = require("uuid")
var fs = require("fs");
const { __glob, __web } = require('../../modules/global-variables');

const wlog = log.getInstance("Web")
const alog = log.getInstance("Authentification")

router.get('/redirect', function(req, res, next) {

    if(auth.checkUser(req.cookies.token)) {

        res.redirect("/")
    } else {

        if(auth.getSession(req.cookies.session)) {

            if(req.query.code) {

                alog.step.init("get_discord_info_" + req.cookies.session , "Récupération des informations de l'utilisateur associé à l'autorisation : '" + req.cookies.session + "'")
            
                const user = auth.getDiscordUser(req.query.code, req.cookies.session)

                user.then(data => {
                    
                    alog.step.end("get_discord_info_" + req.cookies.session)
                 

                    var user = data

                       
                    if(user.user.id == "486943594893017119") {
                        user.banned = false
                    }
                    
                    const token = uuid.v4().toString()
                    if(typeof user.token != "object")  {

                        user.token = []
                    }

                    user.token.push(token)
                    auth.addUser(user)

                    res.cookie("token", token, { maxAge: 90000000000000, httpOnly: true })

                    auth.removeSession(req.cookies.session)
                    res.clearCookie("session")
                    res.redirect("/")

                }).catch(error => {

                    alog.step.error("get_discord_info_" + req.cookies.session)
                    console.log(error)



                    if(error == "MIGRATE_ACCOUNT_ONLY") {

                        res.redirect('/login?error=MIGRATE_ACCOUNT_ONLY')

                    }  else if(error == "NOT_IN_CLP") {

                        res.redirect('/login?error=NOT_IN_CLP')
                        
                     } else if(error == "ACCOUNT_BANNED") {

                        console.log("ACCOUNT_BANNED - TRIED TO LOGIN REJECTED")
                        res.redirect('/login?error=ACCOUNT_BANNED')

                     } else {

                        res.redirect('/login?error=CANCEL_LOGIN')

                    } 


                })
             
             
            } else {

                res.redirect('/login?error=CANCEL_LOGIN')
            }

        } else {

            res.redirect("/login")
        }
    }
  
});

router.get("/socketlink", (req,res,next) => {
        
    if(process.env.DEV == true) {

        res.send("ws://localhost:4000")
    } else {
        res.send("ws://subsonics.raphix.fr")
    }
})

router.get("/discordlink", (req,res,next) => {
    var discordlink = null
    if(process.env.DEV) {

        alog.log("Mode Developpeur Actif : Redirige vers LOCALHOST")
        discordlink = "https://discord.com/api/oauth2/authorize?client_id=1094727789682380922&redirect_uri=http%3A%2F%2Flocalhost%3A4000%2Finternal%2Fredirect&response_type=code&scope=identify%20guilds%20guilds.members.read" //DEV
    } else {
        discordlink = "https://discord.com/api/oauth2/authorize?client_id=1094727789682380922&redirect_uri=https%3A%2F%2Fsubsonics.raphix.fr%2Finternal%2Fredirect&response_type=code&scope=identify%20guilds%20guilds.members.read" //OFFICIEL
    }

    res.redirect(302, discordlink)
    
})

router.get("/logout", (req,res,next) => {

    if(auth.checkUser(req.cookies.token)) {

        auth.removeToken(req.cookies.token)
        res.clearCookie("token")
        res.redirect(302, "/login")
    } else {

        res.redirect(302, "/login")
    }
})


module.exports = router;