const router = require(`express`).Router()
const createError = require('http-errors')
const carsModel = require(`../models/cars`)

const jwt = require('jsonwebtoken')
const fs = require('fs')
const JWT_PRIVATE_KEY = fs.readFileSync(process.env.JWT_PRIVATE_KEY_FILENAME, 'utf8')

const multer = require('multer')
var upload = multer({dest: `${process.env.UPLOADED_FILES_FOLDER}`})


// read all records
router.get(`/cars`, (req, res, next) =>
{
    //user does not have to be logged in to see car details
    carsModel.find({})
    .then(data =>
    {
        res.json(data)
    })
    .catch(err => next(err))
})

router.get(`/cars/photo/:filename`, (req, res, next) =>
{
    fs.readFile(`${process.env.UPLOADED_FILES_FOLDER}/${req.params.filename}`, 'base64', (err, fileData) =>
    {
        if(fileData)
        {
            res.json({image: fileData})
        }
        else
        {
            res.json({image: null})
        }
    })
})


// Read one record
router.get(`/cars/:id`, (req, res, next) =>
{
    jwt.verify(req.headers.authorization, JWT_PRIVATE_KEY, {algorithm: "HS256"}, (err, decodedToken) =>
    {
        if(err)
        {
            next(createError(403, `User is not logged in`))
        }
        else
        {
            carsModel.findById(req.params.id)
            .then(data =>
            {
                res.json(data)
            })
            .catch(err => next(err))
        }
    })
})


// Add new record
router.post(`/cars`, upload.array("carPhotos", parseInt(process.env.MAX_NUMBER_OF_UPLOAD_FILES_ALLOWED)), (req, res, next) =>
{
    jwt.verify(req.headers.authorization, JWT_PRIVATE_KEY, {algorithm: "HS256"}, (err, decodedToken) =>
    {
        if(err)
        {
            next(createError(403, `User is not logged in`))
        }
        else
        {
            if(decodedToken.accessLevel >= process.env.ACCESS_LEVEL_ADMIN)
            {
                // Use the new car details to create a new car document                
                let carDetails = new Object()

                carDetails.model = req.body.model
                carDetails.colour = req.body.colour
                carDetails.year = req.body.year
                carDetails.price = req.body.price

                // add the car's photos to the carDetails JSON object
                carDetails.photos = []

                req.files.map((file, index) =>
                {
                    carDetails.photos[index] = {filename: `${file.filename}`}
                })

                carsModel.create(carDetails)
                .then(data =>
                {
                    res.json(data)
                })
                .catch(err => next(err))
            }
            else
            {
                next(createError(403, `User is not an administrator, so they cannot add new records`))
            }
        }
    })
})


// Update one record
router.put(`/cars/:id`, (req, res, next) =>
{
    jwt.verify(req.headers.authorization, JWT_PRIVATE_KEY, {algorithm: "HS256"}, (err, decodedToken) =>
    {
        if(err)
        {
            next(createError(403, `User is not logged in`))
        }
        else
        {
            carsModel.findByIdAndUpdate(req.params.id, {$set: req.body})
            .then(data =>
            {
                res.json(data)
            })
            .catch(err => next(err))
        }
    })
})


// Delete one record
router.delete(`/cars/:id`, (req, res, next) =>
{

    jwt.verify(req.headers.authorization, JWT_PRIVATE_KEY, {algorithm: "HS256"}, (err, decodedToken) =>
    {
        if(err)
        {
            next(createError(403, `User is not logged in`))
        }
        else
        {
            if(decodedToken.accessLevel >= process.env.ACCESS_LEVEL_ADMIN)
            {
                carsModel.findByIdAndDelete(req.params.id)
                .then(data =>
                {
                    res.json(data)
                })
                .catch(err => next(err))
            }
            else
            {
                next(createError(403, `User is not an administrator, so they cannot add new records`))
            }
        }
    })
})

module.exports = router