const MONGO_DB_URL = "mongo.lpaconsulting.fr"
const CAPTCHA_ERROR_COLLECTION_PREFIX = "CAPTCHA_ERROR_"
const BLACK_LIST = "BLACK_LIST"
const DB_NAME = "appointment"
const COLLECTION_NAME = "appointment"
const ACCEPTED_APPOINTMENT_LIST = "ACCEPTED_APPOINTMENT_LIST"
const BLACK_LIST_COLLECTION_NAME = "BLACK_LIST"
const LINKS_TO_VALIDATE = "LINKS_TO_VALIDATE"
const {MongoClient} = require('mongodb');
const ReserveResultPojo = require("../models/ReserveResultPojo");
require("../models/ContactPojo");

function formatDate(date) {
    let d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2)
        month = '0' + month;
    if (day.length < 2)
        day = '0' + day;

    return [year, month, day].join('-');
}

class MongoManager {
    constructor() {
        //init mongoDb
        let uri = `mongodb://appointment:Rdv%402022@${MONGO_DB_URL}/appointment`
        this.client = new MongoClient(uri)
    }

    async connect() {
        await this.client.connect()
        this.db = this.client.db("appointment")
    }

    async getAllSuccessfulItemsForDay(day) {
        return await this.db.collection(day).find().toArray()
    }

    async getAllAcceptedAppointments() {
        return await this.db.collection(ACCEPTED_APPOINTMENT_LIST).find().toArray()
    }

    async saveReserveToDb(reservePojo) {
        let collectionName = formatDate(new Date())
        return await this.db.collection(collectionName).replaceOne({'_id': reservePojo.id,}, reservePojo, {upsert: true})
    }

    async saveBlackListToDb(contact) {
        return await this.db.collection(BLACK_LIST_COLLECTION_NAME).replaceOne({'_id': contact.mail,}, contact, {upsert: true})
    }

    async removeFromBlackList(contact) {
        const query = {_id: contact.mail};
        await this.db.collection(BLACK_LIST_COLLECTION_NAME).deleteOne(query);
    }

    async removeFromToValidateList(url) {
        const query = {_id: url};
        await this.db.collection(LINKS_TO_VALIDATE).deleteOne(query);
    }

    async getAllBlackedListItems() {
        return await this.db.collection(BLACK_LIST_COLLECTION_NAME).find().toArray()
    }

    async linkValidatedFor(urlValidated) {
        let splitedUrl = urlValidated.split("/");
        let id = splitedUrl[splitedUrl.length - 1];
        let collectionName = formatDate(new Date());
        return await this.db.collection(collectionName).updateOne({'_id': id,}, {
            "$set": {
                "url_validated": true,
                "validated_at": new Date().toLocaleString()
            }
        }, {upsert: false})
    }

    async getAllLinkToValidate() {
        return await this.db.collection(LINKS_TO_VALIDATE).find().toArray()
    }
}


module.exports = {MongoManager, formatDate}