var express = require('express');
var app = express();
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var cors = require('cors');

app.use(cors());

var bodyParser = require('body-parser');
//var methodOverride = require('method-override');

mongoose.connect('mongodb://127.0.0.1:27017/TodoAppDB');

app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
//app.use(methodOverride());

// define DB
var schema = new Schema({
	taskname: String,
	Done: Boolean,
	details: String
});

var Todo = mongoose.model('tasks', schema);

app.get('/todolist', function(req, res) {
	console.log("I recived a get request.");

	Todo.find(function(err, tasks) {
		res.json(tasks);
	});

});

app.post('/todolist', function(req, res) {
	Todo.create(req.body, function(err, tasks) {
		res.json(tasks);
	});
});

app.put('/todolist/:id', function(req, res){
	console.log(req.body);
	 Todo.update({_id:req.params.id},req.body,{upsert:true},function(err) {
		if(!err) {
			 res.send('updated');
		}
		else {
			console.log(err);
			res.send(404);
		}
	});
});

app.delete('/todolist/:id', function(req, res){
	 Todo.remove({_id: req.params.id}, function(err) {
		if(!err) {
			 res.send('deleted');
		}
		else {
			console.log(err);
			res.send(404);
		}
	});
});




app.listen(8080);
console.log("Server started on port 8080...");