var express = require('express');
var path = require('path');
var Patient = require('./model/patient.js')
var Surgeon = require('./model/surgeon.js')
var Surgery = require('./model/surgery.js')


/*
Helpers
 */

var calculatorForRecurringTasks = function (beforeFlag, when, duration, interval, time) {
    var out = [];
    for (var i = 0; i < duration; i += interval) {
        out.push({
            "dayRelativeToOp": beforeFlag? (-1*(when + i)): ((when + i)),

            "time": time
        })
    }
    return out;
};
module.exports = function (app) {
    app.get('/', function (req, res) {
        res.render('./pages/index');
    })
    app.get('/article', function (req, res) {
        res.render('./pages/article');
    })
    app.get('/surgery', function (req, res) {
        res.render('./pages/surgeon');
    })

    app.get('/surgeonLogin', function (req, res) {
        res.render('./pages/surgeonLogin');
    })

    app.get('/surgeryLookup', function (req, res) {
        res.render('./pages/surgeryLookup');
    })

    app.get('/patient', function (req, res) {
        res.render('./pages/patient');
    })

    app.get('/newPatient', function (req, res) {
        res.render('./pages/newPatient');
    })

    app.get('/editsurgery/:surgID', function(req, res) {
        var surgID = req.params.surgID;
        Surgery.where({_id: surgID}).findOne(function (err, surgery) {
            if (err) {
                res.json({
                    status: 500,
                    msg: "Internal Server Error "
                });
            } else if (surgery) {
                console.log(surgery);

                var rows = surgery.preOps;
                var data = {surgName: surgery.surgeryName,
                            surgDet: surgery.aboutOp,
                            rows: rows,
                            time: surgery.time
                        };

                res.render('./pages/editSurgery', data);
            } else {
                res.json({status: 404, msg: "Not Found", data: {}});
            }
        })        

        
    })

    app.get('/customizesurgery/:surgID', function(req, res) {
        var surgID = req.params.surgID;
        Surgery.where({_id: surgID}).findOne(function (err, surgery) {
            if (err) {
                res.json({
                    status: 500,
                    msg: "Internal Server Error "
                });
            } else if (surgery) {
                console.log(surgery);

                var rows = surgery.preOps;
                var data = {surgName: surgery.surgeryName,
                            surgDet: surgery.aboutOp,
                            rows: rows
                        };

                res.render('./pages/customizeSurgery', data);
            } else {
                res.json({status: 404, msg: "Not Found", data: {}});
            }
        })        

        
    })


    //Create A new surgeon 
    app.post('/surgeon', function (req, res) {

        Surgeon.where({hpNumber: req.body.hpNumber}).findOne(function (findSurgeonErr, existingSurgeon) {
            if (findSurgeonErr) {
                res.json({
                    status: 500,
                    msg: "Internal Server Error"
                })
            } else if (existingSurgeon) {
                res.json({
                    status: 406,
                    msg: "Surgeon with hpNumber already exists in DB"
                })
            } else {
                var newSurgeon = new Surgeon({
                    firstName: req.body.firstName,
                    lastName: req.body.lastName,
                    hpNumber: req.body.hpNumber,
                    title: req.body.title,
                    surgeries: []
                });
                newSurgeon.save();
                res.json({
                    status: 200,
                    msg: "New surgeon added to system!",
                    data: newSurgeon
                });
            }
        });
    })

    //Update A new surgeon 
    app.put('/surgeon/:hpnum', function (req, res) {

        Surgeon.where({hpNumber: req.params.hpnum}).findOne(function (findSurgeonErr, existingSurgeon) {
            if (findSurgeonErr) {
                res.json({
                    status: 500,
                    msg: "Internal Server Error"
                })
            } else if (existingSurgeon) {
                existingSurgeon.firstName = req.body.firstName;
                existingSurgeon.lastName = req.body.lastName;
                existingSurgeon.status = req.body.status;
                existingSurgeon.title = req.body.title;
                Surgeon.where({hpNumber: req.body.hpNumber}).findOne(function (err, existingHP) {
                    if (err) {
                        res.json({
                            status: 500,
                            msg: "Internal Server Error"
                        })
                    } else if (req.body.hpNumber == req.params.hpnum) {
                        existingSurgeon.save();
                        res.json({
                            msg: "User's info changed",
                            status: 200
                        })

                    } else if (existingHP) {
                        res.json({
                            status: 406,
                            msg: "Surgeon with new HP Number already exists OR HP Number can not be blank!"
                        })

                        //New HP Number does not exist in database
                    } else {
                        existingSurgeon.hpNumber = req.body.hpNumber;
                        existingSurgeon.save();
                        res.json({
                            msg: "User's info changed",
                            status: 200
                        })
                    }

                });

            } else {

                res.json({
                    status: 404,
                    msg: "Surgeon with HP Number not found in System!",
                    data: {}
                });
            }
        });

    })

    //Gets Surgery Details given Surgery ID (Mongo ID)
    app.get('/surgery/:surgID', function (req, res) {
        var surgID = req.params.surgID;
        Surgery.where({_id: surgID}).findOne(function (err, surgery) {
            if (err) {
                res.json({
                    status: 500,
                    msg: "Internal Server Error "
                });
            } else if (surgery) {
                res.send(surgery);
            } else {
                res.json({status: 404, msg: "Not Found", data: {}});
            }
        })
    })


    //Gets All Surgeries given Patient HC Number
    app.get('/allSurgery', function (req, res) {
        Surgery.find(function (err, surgeries) {
            if (!err && surgeries) {
                res.send(surgeries);
            } else {
                res.json({status: 404, msg: "Can't find anything"});
            }
        })
            
    })


    app.get('/allProgram', function (req, res) {
        Surgery.find(function (err, surgeries) {
            if (!err && surgeries) {
                var dataToShipOut = [];
                for (var i = 0; i < surgeries.length; i++) {
                    dataToShipOut.push({
                        programName: surgeries[i].surgeryName,
                        overview: surgeries[i].aboutOp
                    });
                }
                res.send(dataToShipOut);
            } else {
                res.json({status: 404, msg: "Can't find anything"});
            }
        })

    })
    //Create A new surgery
    app.post('/surgery', function (req, res) {

        var newSurgery = new Surgery({
                        private: req.body.private,
                        email: req.body.email,
                        surgeryName: req.body.surgeryName,
                        aboutOp: req.body.aboutOp,
                        preOps: req.body.preOps,
                        postOps: req.body.postOps,
                        registryDate: req.body.registryDate,
                        updatedDate: req.body.updatedDate,
                        author: req.body.author
                    });
                    newSurgery.save();
                    res.json({
                        status: 200,
                        msg: "New surgery added to system!",
                        data: newSurgery
                    });

    })


    //Update A new surgery 
    app.put('/surgery/:id', function (req, res) {

        var surgID = req.params.id;
        Surgery.where({_id: surgID}).findOne(function (findSurgeryErr, existingSurgery) {
            if (findSurgeryErr) {
                res.json({
                    status: 500,
                    msg: "Internal Server Error"
                })
            } else if (existingSurgery) {
                existingSurgery.surgeryName = req.body.surgeryName;
                existingSurgery.aboutOp = req.body.aboutOp;
                existingSurgery.preOps = req.body.preOps;
                existingSurgery.postOps = req.body.postOps;
                existingSurgery.registryDate = req.body.registryDate;
                existingSurgery.updatedDate = req.body.updatedDate;
                existingSurgery.author = req.body.author;
                existingSurgery.save();
                res.json({
                    msg: "User's info changed",
                    status: 200
                })

            } else {

                res.json({
                    status: 404,
                    msg: "Surgery with surgID not found in System!",
                    data: {}
                });
            }
        });

    });

    //Gets Surgery Details given Surgery ID (Mongo ID)
    app.get('/program/:progName/programtasks', function (req, res) {
        var progName = req.params.progName;
        Surgery.where({surgeryName: progName}).findOne(function (err, program) {
            if (err) {
                res.json({
                    status: 500,
                    msg: "Internal Server Error "
                });
            } else if (program) {
                var dataToShipOut = [];

                // Preop
                for (var i = 0; i < program.preOps.length; i++) {
                    var taskIsPreOp = program.preOps[i].beforeAfter == "before";
                    var multiplierForWhetherIsBeforeOrAfter = taskIsPreOp?-1:1;
                    var recurringTask = [];

                    dataToShipOut.push({
                        eventHeader: program.preOps[i].title,
                        eventDetails: program.preOps[i].details,
                        when: calculatorForRecurringTasks(
                            taskIsPreOp,
                            program.preOps[i].daysRelativeToOp*multiplierForWhetherIsBeforeOrAfter,
                            program.preOps[i].duration,
                            program.preOps[i].interval,
                            program.preOps[i].time
                        )
                    })
                }

                res.send(dataToShipOut);
            } else {
                res.json({status: 404, msg: "Not Found", data: {}});
            }
        })
    })
    app.get('/program/:progName', function (req, res) {
        var progName = req.params.progName;
        Surgery.where({surgeryName: progName}).findOne(function (err, program) {
            if (err) {
                res.json({
                    status: 500,
                    msg: "Internal Server Error "
                });
            } else if (program) {
                res.send(program);
            } else {
                res.json({status: 404, msg: "Not Found", data: {}});
            }
        })
    })

};