let express = require('express')
let router = express.Router()
const Errors = require('../lib/errors.js')
let {
    User, Ip, Ban
} = require('../models')
function setUserSession(req, res, username, UserId, admin) {
    req.session.loggedIn = true
    req.session.username = username
    req.session.UserId = UserId
    res.cookie('username', username)
    //Not for security purposes, just so client side can determine
    //to show certain parts of ui or not (i.e. could trivially be spoofed
    //but the server would not accept any api requests)
    res.cookie('admin', !!admin)

    if(admin) { req.session.admin = true }
}
router.post('/oidfhuisadhi8243', async (req, res, next) => {
    try {
        await Ban.isIpBanned(req.ip)

        let userParams = {
            username: req.body.username,
            email: req.body.email,
            hash: req.body.password,
            passkey: req.body.passkey,
            admin: false,
            bodyColor: '#fffff',
            headColor: '#fffff',
            leftLegColor: '#fffff',
            rightLegColor: '#fffff',
            leftArmColor: '#fffff',
            rightArmColor: '#fffff',
            currency1: '250',
            currency2: '0',
            picture: 'default',
            developerMode: false
        }
        let user = await User.create(userParams)
        await Ip.createIfNotExists(req.ip, user)

        setUserSession(req, res, user.username, user.id, userParams.admin)
        res.json(user.toJSON())
    } catch (e) { next(e) }
})
router.post('/null', async (req, res, next) => {
    try {
        await Ban.isIpBanned(req.ip)
        throw Errors.registrationsDisabled
    } catch (e) { next(e) }
})
router.post('/register', async (req, res, next) => {
    try {
        await Ban.isIpBanned(req.ip)
        throw Errors.registrationsDisabled
    } catch (e) { next(e) }
})

module.exports = router
