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

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 Schema for all table in the DB

//tasks Schema
var TaskSchema = new Schema({
	task_name: String,
	task_status: Boolean,
	DueDate: Date,
	Project_id: { type: Schema.Types.ObjectId, ref: 'Project' }
	//CreatedById: [{ type: Schema.Types.ObjectId, ref: 'User' }]
});

var Task = mongoose.model('tasks', TaskSchema); // task model

//projects Schema
var ProjectSchema = new Schema({
	project_name: String,
	//CreatedById: [{ type: Schema.Types.ObjectId, ref: 'User' }],
	project_status: Boolean
});

var Project = mongoose.model('projects', ProjectSchema);


//===============================================================================

//Task query

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

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

});

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

app.put('/tasks/:id', function(req, res){
	console.log(req.body);
	 Task.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('/tasks/:id', function(req, res){
	 Task.remove({_id: req.params.id}, function(err) {
		if(!err) {
			 res.send('deleted');
		}
		else {
			console.log(err);
			res.send(404);
		}
	});
});

// ==================================================================================
//Projects query

app.get('/projects', function(req, res) {

	Project.find().exec(function(err, projects) {
		res.json(projects);
	});

});

app.post('/projects', function(req, res) {
	Project.create(req.body, function(err, projects) {
		res.json(projects);
	});
});

app.put('/projects/:id', function(req, res){
	console.log(req.body);
	 Project.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('/projects/:id', function(req, res){
	 Project.remove({_id: req.params.id}, function(err) {
		if(!err) {
			 res.send('deleted');
		}
		else {
			console.log(err);
			res.send(404);
		}
	});
});

// ==================================================================================


// Yogendra

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