var express = require('express');
var app = express();

// create router() object
var router = express.Router();

// using Router as middleware..  here just grabbing the hit method.
// doing this before the router gets to 'respond' to hit
router.use(function(req, res, next) {
    console.log('/' + req.method);
    next();
});

// this middleware will get the id param and check if its 0 else to to next router
router.use('/user/:id', function(req,res,next) {
    if(req.params.id == 0) {
        res.json({'message': "you must pass ID other than 0"});
        }
        else next();
});

// provide all routes here, this one is for Home page
router.get('/', function(req, res) {
    res.sendFile(__dirname + '/public/index.html');
    //res.json({"message" : "Hello World"});
});
router.get('/about', function(req, res) {
    res.sendFile(__dirname + '/public/about.html');
});

// here is how we use a parameter in a route (router)
router.get('/user/:id', function(req,res) {
    res.json({'message': "Hello "+req.params.id});
});

// this is how we handle 494 errors in the basic sense
app.use('*', function(req,res) {
    res.sendFile(__dirname + '/public/404.html');
    //res.status(404).send('404');
});

// tell express to use this router with /api before.
// you can put just '/' if you dont want any sub path before routes.
app.use('/api',router);

//listen to this port
app.listen(3000, function() {
    console.log('live at port 3000');
});