import express from 'express';
import passport from 'passport';
import { DB_NAME, getDatabaseClient } from '../db-utils';
import { Word } from '../shared/models/word';

export const libraryRoutes = express.Router();

export const jwtAuthentication = passport.authenticate('jwt', { session: false });

// Get All Words

libraryRoutes.get('/all/', jwtAuthentication, async (request, response) => {
    const wordCollection = getDatabaseClient().db(DB_NAME).collection<Word>('words');

    const allWords = await wordCollection.find().toArray();

    response.status(200);
    response.json(allWords);

    return;
});

libraryRoutes.get('/search/', jwtAuthentication, async (request, response) => {
    const wordCollection = getDatabaseClient().db(DB_NAME).collection<Word>('words');

    if (!request.query.name) {
        response.status(400);
        response.send("Fill in the word to search for");
        return;
    }

    const allWords = await wordCollection.find({
        name: {'$regex':'^' + request.query.name.toString().toUpperCase() + '*'}
    }).toArray();

    response.status(200);
    response.json(allWords);

    return;
});

libraryRoutes.post('/add/', jwtAuthentication, async (request, response) => {
    const wordCollection = getDatabaseClient().db(DB_NAME).collection<Word>('words');

    if (!request.body.name || request.body.grammaticalDetails) {
        response.status(400);
        response.send("Missing name or grammatical details");
        return;
    }

    if (!request.body.grammaticalDetails.type || !request.body.grammaticalDetails.description || !request.body.grammaticalDetails.context || !request.body.grammaticalDetails.examples) {
        response.status(400);
        response.send("Missing params in grammatical details");
        return;
    }

    await wordCollection.insertOne({
        name: request.body.name,
        languageType: 'ENGLISH',
        grammaticalDetails: request.body.grammaticalDetails,
    });

    return;
});
