﻿var Express         = require('express'),
    Path            = require('path'),
    LootRouter      = require('./Routes/LootRouter'),
    Mongoose        = require('mongoose'),
    BodyParser      = require('body-parser'),

    Loot            = require('./Models/Loot');


var uristring =
    process.env.MONGOLAB_URI ||
    'mongodb://lootuser:lootuser123@ds043971.mongolab.com:43971/heroku_app34016870';

Mongoose.connect(uristring, function (err, res) {
    if (err) {
        console.log("Error connecting " + err);
    } else {
        console.log("Connected");
    }
});

var app = Express();

app.set('port', (process.env.PORT || 5000));

app.use(Express.static(Path.join(__dirname, '../public')));
app.use(BodyParser.json({ extended: true }));
app.use('/api', LootRouter);


app.get('/', function (request, response) {
    response.render('index.html');
});

app.get('/api/loot', function(request, response)  {
    return Loot.find(function (err, loots) {
        if (!err) {
            response.json(loots);
        } else {
            console.log(err);
            response.send(err);
        }
    });
});

app.post('/api/loot', function (request, response) {
    var loot = new Loot();

    loot.name = request.body.name;
    loot.quantity = request.body.quantity;
    loot.special = request.body.special;

    loot.save(function (err) {
        if (err) {
            response.send(err);
        } else {
            response.json(loot);

        }
    });
});


app.get('/api/loot/:id', function (request, response) {
    return Loot.findById(request.params.id, function (err, loot) {
        if (!err) {
            response.json(loot);
        } else {
            console.log(err);
            response.send(err);
        }
    });
});

app.put('/api/loot/:id', function (request, response) {
    return Loot.findById(request.params.id, function (err, loot) {
        if (!err) {

            loot.name = request.body.name;
            loot.quantity = request.body.quantity;
            loot.special = request.body.special;

            return loot.save(function (err) {
                if (err)  {
                    response.send(err);
                } else {
                    response.json(loot);
                }
            })
        }
    });
});

app.delete('/api/loot/:id', function (request, response) {
    return Loot.remove({
        _id: request.params.id
    }, function(err) {
        if (err) {
            response.send(err);
        }
        response.json({message: "Success"});
    });
});

app.listen(app.get('port'), function () {
    console.log("Fellesloot server is running at localhost:" + app.get('port'));
});
