import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import config from '../src/config';

import * as db from './dbUtils/index';

// Initialization of express application
const app = express();

// Set up connection to database
db.setUpConnection();

// Using bodyParser middleware
app.use( bodyParser.json() );

// Allow requests from any origin
app.use( cors({ origin: '*' }) );

// Use static build for production
if (config.serveStatic) {
    app.use(express.static(config.publicPath));
    app.use('/', express.static(config.publicPath));
}

const port = normalizePort(config.serverPort);
app.set('port', port);

function normalizePort(val) {
    const port = parseInt(val, 10);

    if (isNaN(port)) {
        // named pipe
        return val;
    }

    if (port >= 0) {
        // port number
        return port;
    }

    return false;
}

// RESTful api handlers
app.get('/products', (req, res) => {
    db.listNoCategoryProducts().then(data => res.send(data));
});

app.get('/products/:categoryId', (req, res) => {
    db.listCategoryProducts(req.params.categoryId).then(data => res.send(data));
});

app.post('/product', (req, res) => {
    db.createProductItem(req.body).then(data => res.send(data));
});

app.post('/updproduct/:id', (req, res) => {
    db.updateProductItem(req.body, req.params.id).then(data => res.send(data));
});

app.delete('/product/:id', (req, res) => {
    db.deleteProductItem(req.params.id).then(data => res.send(data));
});

app.get('/categories', (req, res) => {
    db.listAllCategories().then(data => res.send(data));
});

app.post('/category', (req, res) => {
    db.createCategoryItem(req.body).then(data => res.send(data));
});

app.delete('/category/:id', (req, res) => {
    db.moveCategoryProducts(req.params.id).then(data => res.send(data));
    db.deleteCategoryItem(req.params.id).then(data => res.send(data));
});

const server = app.listen(port, function() {
    console.log(`Server is up and running on port ${port}`);
});