const express = require('express');
const initiateQuery = require("../utils/query")
const { mongoose, PartyModel } = require('../utils/mongo');
var router = express.Router();
const { currentGame, resetGame } = require("../utils/partyManager");
const { ping } = require("../utils/udp");


mongoose
    .connect(process.env.MONGO, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    })
    .catch((err) => console.log("CONNECT", err));


router.get('/get/', function (req, res) {
    (async () => {

        let response = "";
        initQuery = initiateQuery(req.query);
        const users = await PartyModel
            .find(req.query)
            .limit(parseInt(initQuery[2]))
            .skip(parseInt(initQuery[2]) * parseInt(initQuery[1]))
            .sort(initQuery[3]);

        response = res.send(users)

        return response;
    })();
});

router.post('/new/', function (req, res) {
    resetGame();
    currentGame.writeWinCondition(req.body);
    res.send(currentGame.context());
});

router.post('/setup/', function (req, res) {
    if (!currentGame.startTime) {
        currentGame.setup(req.body);
        res.send(currentGame.context());
    } else {
        res.send({
            error: {
                message: "game is already start"
            }
        });
    }
});

router.get('/ping', function (req, res) {
    ping();
    res.send(currentGame.context());
});

router.get('/ping/:key', function (req, res) {
    ping(req.params.key);
    res.send(currentGame.context());
});

router.get('/start/', function (req, res) {
    currentGame.start()
    res.send(currentGame.context());
});

router.get('/save/', function (req, res) {
    s = async () => {
        if (currentGame.startTime && currentGame.finishTime) {
            await PartyModel.create(
                currentGame.context()
            );
            res.send(currentGame.context());
        } else {
            if (!currentGame.startTime) {
                res.send({
                    error: {
                        message: "game is not start"
                    }
                });
            } else if (!currentGame.finishTime) {
                res.send({
                    error: {
                        message: "game is not finish"
                    }
                });
            }
        }
    }
    s();
});

router.get('/current/', function (req, res) {
    res.send(currentGame.context());
});

router.get('/finish/', function (req, res) {
    currentGame.finish()
    res.send(currentGame.context());
});

router.post('/update/:key/', function (req, res) {
    currentGame.updatePlayer(req.params.key, req.body)
    res.send(currentGame.context());
});



module.exports = router;
