// https://mongoosejs.com/docs/connections.html

const mongoose = require("mongoose");
mongoose.Promise = global.Promise;
mongoose.connect(
    'mongodb://localhost:27017/dbtodo?readPreference=primary&appname=TodoListMongo&directConnection=true&ssl=false',
    {
        useNewUrlParser: true, 
        useUnifiedTopology: true         
    }
).then
(
    () => 
    {
        console.log("connected succesfully");
    },
    err =>
    {
        console.log("connection failed");

    }
);

const Schema = mongoose.Schema;
var TaskSchema = new Schema({
    name: {
        type:String,
        required: 'name is required'
    }
});
task = mongoose.model('task',TaskSchema);

const http  = require ('http');  // to create server
const url   = require('url');    // to parse url
const { Console } = require("console");
const BASIC_API_PORT = 3998;

const app = http.createServer(
    async (req, res) => {
        const parsedURL = url.parse(req.url, true);
        if (req.method === 'GET'  && parsedURL.pathname.startsWith('/api/tasks'))
        {
            task.find({}, function(err, tasks) {
                if(err)
                {
                    res.statusCode = 400;
                    res.end(err);
                }
                else
                {
                    res.statusCode = 200;
                    res.end(JSON.stringify(tasks));
                }

            });
        }
        /*
        else if (methode : DELETE route : /api/del param : id )
        {
            fonction remove prend en paramètre _id qui est l'id du document à effacer
        }
        */
        else if (req.method === 'DELETE' && parsedURL.pathname.startsWith('/api/del')) 
        {
            if(!parsedURL.query.id)
            {
                res.statusCode = 400;
                res.end("missing required argument id");   
            }
            else
            {
                console.log("Received :" + parsedURL.query.id);
                
                task.remove({ _id : parsedURL.query.id }, function (err,task) {
                    if(err)
                    {
                        res.statusCode = 400;
                        res.end(err);
                    }
                    else
                    {
                        res.statusCode = 200;
                        res.end('task '+parsedURL.query.id+' deleted.');
                    }

                });
            }            
        }        
        else if (req.method === 'POST' && parsedURL.pathname.startsWith('/api/task')) 
        {
            if(!parsedURL.query.name)
            {
                res.statusCode = 400;
                res.end("missing required argument name");   
            }
            else
            {
                console.log("Received :" + parsedURL.query.name);
                var new_task = new task(parsedURL.query);
                new_task.save(function(err,task){
                    if(err)
                    {
                        res.statusCode = 400;
                        res.end(err);
                    }
                    else
                    {
                        res.statusCode = 200;
                        res.end(JSON.stringify(task));
                    }

                });
                console.log(new_task);
            }            
        } 
        else 
        {
            res.statusCode = 400;
            res.end("mongoose API Endpoint Not Supported");
        }

    }

);

app.listen(BASIC_API_PORT);        


console.log('server mongoose test started');