/*
 * Main database access functions
 */
var common,
    model = {};

const dbs = {
    /* Method API route
     * <- to server
     * -> to client
     * Description
     */
    routes: {
        "msg/ids": {
            /* GET /api/msg/ids [no args]
             * -> Array of message schema object ids
             * Get ALL known message ids
             */
            get: function (req, res) {
                model.Messages.find({}, {
                        _id: true
                    }).exec()
                    .then(results => {
                        //selects id from message:
                        var parsed = [];
                        for (var i in results) {
                            parsed.push(results[i]._id);
                        }
                        res.send(parsed);
                    })
                    .catch(err => {
                        console.log(err);
                        res.status(500).json(err);
                    });
            },
        },
        "msg/id": {
            params: ":id",
            /* GET /api/msg/id/[massage-id]
             * -> Message schema
             * Get a particular message
             */
            get: function (req, res) {
                model.Messages.findById(req.params.id).exec(function (err, result) {
                    if (err) {
                        console.log(err);
                        res.status(404).json(err);
                    } else {
                        //console.log(JSON.stringify(result));
                        res.json(result);
                    }
                });
            },
        },
        "msg/search": {
            params: ":phrase",
            /* GET /api/msg/id/[massage-id]
             * -> Message schema
             * Get a particular message
             */
            get: function (req, res) {
                model.Messages.find({
                        $text: {
                            $search: req.params.phrase
                        }
                    })
                    .sort({
                        tag: -1
                    })
                    .exec().then(results => {
                        //selects id from message:
                        var parsed = [];
                        for (var i in results) {
                            parsed.push(results[i]._id);
                        }
                        res.send(parsed);
                    })
                    .catch(err => {
                        console.log(err);
                        res.status(500).json(err);
                    });
            },
        },
        "msg": {
            /* POST /api/msg
             * <- Message schema
             * -> Message schema
             * Create a new message
             */
            post: function (req, res) {
                /*
                if ( !(req.body.tags instanceof Array) ) {
                    return res.status(400).json({ error: "bad request" });
                }*/
                //console.log("Subject: "+JSON.stringify(req.body));

                model.Messages.create({
                    subject: req.body.subject,
                    message: req.body.message,
                    user: req.body.user,
                    tag: req.body.tag
                }, function (err, result) {
                    if (err) {
                        return res.status(401).json(err.message);
                    } else {
                        res.json({
                            message: "Message created!!"
                        });
                    }
                    if (result == null) {
                        return res.status(500).json("Can not create message.")
                    }
                });
            },
            /* PUT /api/msg
             * <-
             * ->
             * Update a message
             */
            //put: function(req, res) {},
        },
        "tag/ids": {
            /* GET /api/tag/ids [no args]
             * -> Array of tag schema object ids
             * Get ALL known tag ids
             */
            get: function (req, res) {
                model.Tags.find({}, {
                        _id: true
                    }).exec()
                    .then(results => {
                        //selects id from tag:
                        var parsed = [];
                        for (var i in results) {
                            parsed.push(results[i]._id);
                        }
                        res.send(parsed);
                    })
                    .catch(err => {
                        console.log(err);
                        res.status(500).json(err);
                    });
            },
        },
        "tag/id": {
            params: ":id",
            /* GET /api/tag/id/[tag-id]
             * -> Tag schema
             * Get a particular tag
             */
            get: function (req, res) {
                model.Tags.findById(req.params.id)
                    .exec(function (err, result) {
                        if (err) {
                            console.log(err);
                            res.status(404).json(err);
                        } else {
                            //console.log(req.params.id);
                            res.json(result);
                        }
                    });
            },
        },
        "usr/bookmark/ids": {
            /* GET /api/usr/bookmark/ids [no args]
             * -> Array of message schema object ids
             * Get bookmark message ids
             */

            get: function (req, res) {
                model.Users.find({
                    },
                    function (err, result) {
                        if (err) {
                            return res.status(401).json(err.message);
                        } else {
                            var parsed = [];
                            for (var i in result) {
                                parsed.push(result[i].bookmarks);
                            }
                            console.log("bookmarks:" + JSON.stringify(parsed));
                            res.send(parsed);
                        }
                        if (result == null) {
                            return res.status(500).json("Can save bookmark.")
                        }
                    });
            },
        },
        "usr/id": {
            params: ":id",
            /* GET /api/usr/[usr-id]
             * -> User Schema
             * Get a particular user
             */
            get: function (req, res) {
                model.Users.find({
                        _id: req.params.id
                    })
                    .exec(function (err, result) {
                        if (err) {
                            console.log(err);
                            res.status(404).json(err);
                        } else {
                            console.log(result);
                            res.json(result);
                        }
                    });
            },
        },
        "usr": {
            /* POST /api/usr
             * <- User schema
             * -> User schema
             * Create a new user
             */
            post: function(req, res) {
//                console.info(req.body);
                model.Users.create({
                    _id: req.body._id,
                    name: req.body.name,
                    mail: req.body.mail,
                    type: req.body.type,
                    gender: req.body.gender,
                    abos: req.body.abos,
                    bookmarks: req.body.bookmarks,
                    roles: req.body.roles,
                }, function(err, result) {
                    if (err) {
                        console.log(err);
                        return res.status(401).json(err.message);
                    } else {
                        res.json({message: "User created!", user: req.body});
                    }
                    if (result == null) {
                        return res.status(500).json("Can not create user.")
                    }
                });
            },
            /* PUT /api/usr
             * <- User schema
             * -> User schema
             * Change a user
             */
            put: function (req, res) {

                model.Users.find({
                        _id: req.body.userid
                    })
                    .exec(function (err, entry) {
                        if (err) {
                            console.log(err);
                        } else {

                            model.Users.update({
                                _id: req.body.userid
                            }, {
                                bookmarks: req.body.bookmark
                            }, function (err, data) {

                                if (err) {
                                    console.log(err);
                                } else {
                                    res.json({
                                        id: "Bookmark saved"
                                    });
                                }
                                if (data == null) {
                                    return res.status(404).json(err.message);
                                }

                            });

                        }

                        if (entry == null)
                            return res.status(404).json(err.message);
                        // TODO Catch edge cases

                        // TODO Save/Update user
                        /*
                        _id: req.body.id,
                        name: req.body.name,
                        type: req.body.type,
                        roles: req.body.roles,
                        hash: req.body.hash,
                        salt: req.body.salt,
                        pwd: req.body.pwd,
                        abos: req.body.abos,
                        bookmarks: req.body.bookmarks,
                        */
                        // res.json(data);
                    });
            },
        },
    },
    /* Initialize requirements
     *  - DB connection
     *  - DB schemata
     */
    init: function (_common) {
        common = _common;

        /* DB Connection
         * Local db: common.config.dbLocalConn
         * TH    db: common.config.dbConn
         */
        common.mongoose.connect(common.config.dbLocalConn, {
            useNewUrlParser: true
        }).then(() => {
            console.log("Database connected successfully.");
        }).catch(err => {
            console.log('Database connection error.');
            process.exit();
        });
        // Default 'collection.ensureIndex' is deprecated; New is '.createIndexes'
        common.mongoose.set('useCreateIndex', true);

        /* DB Schemata
         * Privat fields:
         * - per model: _list: Elements that are included in list fetch
         * - per entry: _comment: Comment for Admin UI - TODO: not working yet
         */
        var messageSchema = common.mongoose.Schema({
            subject: {
                type: String,
                required: true,
                _comment: ""
            },
            message: {
                type: String,
                required: true,
                _comment: ""
            },
            user: {
                type: String,
                required: true,
                _comment: ""
            },
            tag: {
                type: [String],
                _comment: ""
            },
            //createtime: { type: Date, default: Date.now },
        });
        messageSchema.index({
            "$**": 'text'
        });
        model.Messages = common.mongoose.model('messages', messageSchema);
        model.Messages._list = [""];

        var tagSchema = common.mongoose.Schema({
            name: {
                type: String,
                required: true,
                _comment: ""
            }, //unique
        });
        model.Tags = common.mongoose.model('tags', messageSchema);
        model.Tags._list = [""];

        var userSchema = common.mongoose.Schema({
            _id: { type: String, required: true },
            name:    { type: String,
                      _comment: "" },
            mail: { type: String },
            type: { type: String },
            gender: { type: String },
            pwd:     { type: String,
                      _comment: "" },
            hash: { type: String },
            salt: { type: String },
            abos:    { type: [String],
                      _comment: "" },
            //deactivated: { type: Boolean },
            //host: { type: Boolean },
            bookmarks: { type: [String],
                      _comment: "" },
            sessionid: { type: String },
            roles:   { type: String, required: true,
                      _comment: "" },
        });
        model.Users = common.mongoose.model('users', userSchema);
        model.Users._list = [""];
    },
    models: model,
};


/*
app.get ("/api/msg/search/:phrase", function (req, res) {
    Message.find ({$text: {$search: req.params.phrase}) .then (function (err, results){
        if (err) {
            console.log (err);
            res .status(404) .json (err);
        } else {
            console.log(JSON.stringify(results));
            res.json(results);
        }
    });
});
*/
module.exports = dbs;
