require('dotenv').config()
const express = require('express')
const path = require('path')
const bodyParser = require('body-parser')
const Sequelize = require('sequelize')

const app = express()
const sequelize = new Sequelize(
    process.env.DB_NAME,
    process.env.DB_USERNAME,
    process.env.DB_PASSWORD, {
        host: process.env.DB_HOST,
        dialect: 'mysql',
        pool: {
            max: 5,
            min: 0,
            idle: 10000
        },
        define: {
            timestamps: false
        }
    }
)

// Test the connection and log any errors
sequelize
    .authenticate()
    .then(() => {
        console.log('Connection has been established successfully.')
    })
    .catch(err => {
        console.error('Unable to connect to the database:', err)
    })

// Enable CORS
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*")
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
    next()
})

// Enable delivery of static assets
app.use(express.static(path.join(__dirname, '/public')))

// Enable Body Parser
app.use(bodyParser.json())

// Create model for Monitors, CPU and RAM
const Monitors = sequelize.define('monitors', {
    name: Sequelize.STRING,
    url: Sequelize.STRING
})

const RAM = sequelize.define('ram', {
    monitor_id: Sequelize.INTEGER,
    real: Sequelize.DOUBLE,
    cached: Sequelize.DOUBLE,
    date_time: Sequelize.DATE
})

const CPU = sequelize.define('cpu', {
    monitor_id: Sequelize.INTEGER,
    value: Sequelize.DOUBLE,
    date_time: Sequelize.DATE
})

/**
 * DEFINE APPLICATION ROUTES
 */

app.get('/monitors/all', function(req, res, next) {
    Monitors.findAll().then(monitors => {
        res.send(monitors)
    })
})

app.post('/monitors/create', function(req, res, next) {
    let monitor = req.body

    sequelize.sync()
        .then(() => Monitors.create({
            name: monitor.name,
            url: monitor.url
        }))
        .then(created => {
            res.send(created)
        })
})

app.post('/cpu/get-records', function(req, res, next) {
    let monitor = req.body

    sequelize.sync()
        .then(() => CPU.findAll({
           where: {
               monitor_id: monitor.id
           }
        })
})

app.post('/cpu/create-record', function(req, res, next) {
    let record = req.body

    sequelize.sync()
        .then(() => CPU.create({
            monitor_id: record.monitorId,
            value: record.recordValue,
            date_time: record.recordDate
        }))
        .then(created => {
            res.send(created)
        })
})

app.post('/ram/get-records', function(req, res, next) {
    let monitor = req.body

    sequelize.sync()
        .then(() => RAM.findAll({
            where: {
                monitor_id: monitor.id
            }
        }))
        .then(created => {
            res.send(created)
        })
})

app.post('/ram/create-record', function(req, res, next) {
    let record = req.body

   sequelize.sync()
        .then(() => RAM.create({
            monitor_id: record.monitorId,
            real: record.recordReal,
            cached: record.recordCached,
            date_time: record.recordDate
        }))
        .then(created => {
            res.send(created)
        })
})

app.get('/', function(req, res, next) {
    res.sendfile(__dirname + '/public/index.html')
})

app.get('*', function(req, res, next) {
    res.sendfile(__dirname + '/public/index.html')
})

app.listen(80, function () {
    console.log('App listening on port 80!')
})
        }))
        .then(created => {
            res.send(created)