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

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

const UserRouter = new Router();

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

    return res.render("register.pug", {
        require_token: config.require_token? true : false
    });
});

UserRouter.get(['/', '/login'], async (req, res) => {
    if(req.cookies["jwt"] && jwt.verify(req.cookies["jwt"], config.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),
        enable_chat: config.enable_chat,
        enable_worldmap: config.enable_worldmap
    });
});

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),
        enable_chat: config.enable_chat,
        enable_worldmap: config.enable_worldmap
    });
});

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),
        enable_chat: config.enable_chat,
        enable_worldmap: config.enable_worldmap
    });
});

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),
        enable_worldmap: config.enable_worldmap,
        enable_chat: config.enable_chat,
        worldmap_url: config.worldmap_url
    });
});

export default UserRouter;
