require('dotenv').config();
const express = require('express');
const router = express.Router();
const Project = require('../models/project');
const hostUrl = process.env.HOST_URL


// Get
// router.get('/', async (req, res) => {
//     try {
//         const projects = await Project.find();
//         res.set('Access-Control-Allow-Origin', '*')
//         res.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')

//         res.send({
//             "items": projects,
//             "_links": {
//                 "self": {
//                     "href": hostUrl
//                 }
//             },
//             "pagination": {
//                 "currentpage": 1,
//                 "currentItems": 3,
//                 "totalPages": "",
//                 "totalItems": "",
//                 "_links": {
//                     "first": {
//                         "page": hostUrl,
//                         "href": hostUrl + "/page/1"
//                     },
//                     "last": {
//                         "page": hostUrl,
//                         "href": hostUrl + "/page/1"
//                     },
//                     "previous": {
//                         "page": hostUrl,
//                         "href": hostUrl + "/page/1"
//                     },
//                     "next": {
//                         "page": hostUrl,
//                         "href": hostUrl + "/page/2"
//                     }
//                 }
//             }
//         });
//     }
//     catch (err) {
//         res.status(500).json({ message: err.message });
//     }
// })

router.get('/', async (req, res) => {
    console.log('Get method called')
    if(req.param('start') || req.param('limit')) {
        let start = parseInt(req.param('start'));
        let limit = parseInt(req.param('limit'));
        let firstPage = 1;

        console.log(start);
        console.log(limit);
        // let pageText = req.param('pageNumber');
        // let page = parseInt(pageText);
        // let page = 1;
        let page = Math.ceil(start / limit);
    
        if (page < 1) {
            page++;
        }
        
        try {
            const totalItems = await Project.estimatedDocumentCount().exec().then((data) => {
                console.log(data)
                return data
            })
            const itemLimit = limit;
            console.log('totalItems returned')
            let totalPages = Math.ceil(totalItems/itemLimit);
            let lastPage = totalPages;
            let nextPage = page + 1;
            let prevPage = page - 1;
            console.log('Total Pages:' + totalPages)
            console.log('Total Items:' + totalItems)
    
            if(page > totalPages) {
                page = totalPages;
            }
            
            Project.find()
                .limit(itemLimit)
                .skip(itemLimit * page)
                .sort({
                    date: 'asc'
                })
                .then(projects => {
                    res.send({
                        "items": projects,
                        "_links": {
                            "self": {
                                "href": hostUrl
                            }
                        },
                        "pagination": {
                            "currentPage": page,
                            "currentItems": itemLimit,
                            "totalPages": totalPages,
                            "totalItems": totalItems,
                            "_links": {
                                "first": {
                                    "page": hostUrl,
                                    "href": hostUrl + `?start=${firstPage}&limit=${limit}`
                                },
                                "last": {
                                    "page": hostUrl,
                                    "href": hostUrl + `?start=${lastPage}&limit=${limit}`                                    
                                },
                                "previous": {
                                    "page": hostUrl,
                                    "href": hostUrl + `?start=${prevPage}&limit=${limit}`

                                },
                                "next": {
                                    "page": hostUrl,
                                    "href": hostUrl + `?start=${nextPage}&limit=${limit}`
                                }
                            }
                        }
                    })
                })
                .catch(err => {
                    res.status(500).json({ message: err.message });
                })
        }
        catch(err) {
            res.status(500).json({ message: err.message });
        }            
    }
    else {
        // let pageText = req.param('pageNumber');
        // let page = parseInt(pageText);
        let page = 1;
        // let itemLimit = 2;
    
        if (page < 1) {
            page++;
        }
    
        try {
            // let totalItems
            const totalItems = await Project.estimatedDocumentCount().exec().then((data) => {
                console.log(data)
                return data
            })
            const itemLimit = totalItems;
            console.log('totalItems returned')
            let totalPages = Math.ceil(totalItems/itemLimit) - 1;
            console.log('Total Pages:' + totalPages)
            console.log('Total Items:' + totalItems)
    
            if(page > totalPages) {
                page = totalPages;
            }
    
            Project.find()
                .limit(itemLimit)
                .skip(itemLimit * page)
                .sort({
                    date: 'asc'
                })
                .then(projects => {
                    res.send({
                        "items": projects,
                        "_links": {
                            "self": {
                                "href": hostUrl
                            }
                        },
                        "pagination": {
                            "currentPage": page,
                            "currentItems": itemLimit,
                            "totalPages": totalPages,
                            "totalItems": totalItems,
                            "_links": {
                                "first": {
                                    "page": hostUrl,
                                    "href": hostUrl + `${page}`
                                },
                                "last": {
                                    "page": hostUrl,
                                    "href": hostUrl + `${page}`
                                },
                                "previous": {
                                    "page": hostUrl,
                                    "href": hostUrl + `${page--}`
                                },
                                "next": {
                                    "page": hostUrl,
                                    "href": hostUrl + `${page++}`
                                }
                            }
                        }
                    })
                })
                .catch(err => {
                    res.status(500).json({ message: err.message });
                })
        }
        catch(err) {
            res.status(500).json({ message: err.message });
        }
    }
})

router.get('/:id', getProject, (req, res) => {
    res.send(res.project)
})

// Post
router.post('/', async (req, res) => {

    const project = new Project({
        client: req.body.client,
        description: req.body.description,
        technologies: req.body.technologies
    });

    // project.save().then(data => {
    //     res.status(201).send(data);
    // }).catch(err => {
    //     res.status(500).send({
    //         message: err
    //     });
    // });

    try {
        const newProject = await project.save()
        res.status(201).json(newProject)
    }
    catch (err) {
        res.status(400).json({ message: err.message })
    }
})

// Update
router.put('/:id', getProject, async (req, res) => {
    if (req.body.client != null) {
        res.project.client = req.body.client
    }
    if (req.body.description != null) {
        res.project.description = req.body.description
    }
    if (req.body.technologies != null) {
        res.project.technologies = req.body.technologies
    }

    try {
        const updateProject = await res.project.save();
        res.json(updateProject);
    }
    catch (err) {
        res.status(400).json({ message: err.message })
    }
})

// Delete
router.delete('/:id', getProject, async (req, res) => {
    try {
        await res.project.remove()
        res.status(204).json({ message: 'deleted project' })
    }
    catch (err) {
        res.status(500).json({ message: err.message });
    }
})


// Getting Single Project for manipulation
async function getProject(req, res, next) {
    let project;

    try {
        project = await Project.findById(req.params.id);
        if (project == null) {
            return res.status(404).json({ message: 'Cannot find project' });
        };
    }
    catch (err) {
        return res.status(500).json({ message: err.message });
    }

    res.project = project;
    next()
}

// Options
router.options("/", function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    res.header('Allow', 'GET, POST, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Origin, Content-Type, Authorization, Content-Length, X-Requested-With');
    req.header('Content-Tpe', 'application/json')
    res.send(200);
});

router.options("/:id", function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    res.header('Allow', 'GET, PUT, DELETE, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Origin, Content-Type, Authorization, Content-Length, X-Requested-With');
    req.header('Content-Tpe', 'application/json')
    res.send(200);
});

module.exports = router;