import GroupService from '../services/group.js';
import UserService from '../services/user.js';
import jwt from 'jsonwebtoken';
import config from '../../config.json' with {type: "json"};
import statuses from '../utils/status.js';
import log from '../utils/log.js';

const TAG = "/controllers/group.js";

class GroupController {
    async create(req, res) {
        try {
            let { groupName } = req.params;

            let user = jwt.decode(req.headers.authorization.split(' ')[1], config.secret);
            let status = await GroupService.create(groupName, user.login.id);

            log.info(`New group with name ${groupName} was just created by user ${user.login.username}`);

            UserService.joinGroup(user.login.id, status.id);
            return res.status(200).send("Successfull");
        } catch (e) { return res.status(500).send(log.unknownError(`${TAG}/create: ${e}`)); }
    }
    async join(req, res) {
        try {
            let { groupId } = req.params;

            let user = jwt.decode(req.headers.authorization.split(' ')[1], config.secret);
            let status = await UserService.joinGroup(user.login.id, groupId);

            if (status == statuses.duplicate) return res.status(400).send("Already in group");

            log.info(`User ${user.login.username} has just joined group with ID ${groupId}`);
            return res.status(200).send("Successfull");
        } catch (e) { return res.status(500).send(log.unknownError(`${TAG}/join: ${e}`)); }
    }

    async updatePassword(req, res) {
        try {
            let { groupId } = req.params;
            let { password } = req.body;

            await GroupService.updatePassword(groupId, password);
            log.info(`Password for group with ID ${groupId} was updated`);
            return res.status(200).send("Successfull");

        } catch (e) { return res.status(500).send(log.unknownError(`${TAG}/updatePassword ${e}`)); }
    }
}

export default new GroupController();