import { Router } from 'express';
import jwt from 'jsonwebtoken';
import dotenv from 'dotenv';

import auth from '../middlewares/auth.js';
import UserService from '../services/user.js';

dotenv.config({path: ".env"});

const UserRouter = new Router();

UserRouter.get('/register', async (req, res) => {
    if (req.cookies["jwt"] && jwt.verify(req.cookies["jwt"], process.env.SECRET))
        return res.redirect("/index");

    return res.render("register.pug", {
        require_token: process.env.REQUIRE_TOKEN == "true"? true : false
    });
});

UserRouter.get(['/', '/login'], async (req, res) => {
    if(req.cookies["jwt"] && jwt.verify(req.cookies["jwt"], process.env.SECRET)) {
        return res.redirect("/index");
    }

    return res.render("login.pug");
});

UserRouter.get(['/index', '/skin'], auth.authenticate, async (req, res) => {    
    const username = jwt.decode(req.cookies["jwt"]).username;

    return res.render('skin.pug', {
        username: username,
        can_have_cloak: await UserService.canHaveCloak(username)
    });
});

UserRouter.get('/changepassword', auth.authenticate, async (req, res) => {
    const username = jwt.decode(req.cookies["jwt"]).username;

    return res.render('changepassword.pug', {
        can_have_cloak: await UserService.canHaveCloak(username)
    });
});

UserRouter.get('/chat', auth.authenticate, async (req, res) => {
    const username = jwt.decode(req.cookies["jwt"]).username;

    return res.render('chat.pug', {
        can_have_cloak: await UserService.canHaveCloak(username)
    });
});

UserRouter.get('/worldmap', auth.authenticate, async (req, res) => {
    const username = jwt.decode(req.cookies["jwt"]).username;

    return res.render('worldmap.pug', {
        can_have_cloak: await UserService.canHaveCloak(username)
    });
});

export default UserRouter;