const Images = require('../modules/images');
const Logger = require('../modules/logger');
const Mongoose = require('mongoose');  

const MessageSchema = new Mongoose.Schema({
  "text" : { type: String },
  "image" : { type: String, index: true },
  "isUser" : { type: Boolean, default: false, required: true, index: true },
  "timestamp": { type: Date, default: Date.now() }
});

MessageSchema.pre('findOneAndUpdate', function (next) {
  var message = this;
  
  if (message.image && typeof message.image === 'object') {
    Images.saveMessageImage(message.image, (err, filename) => {
      if (err) {
        Logger.error('[MessageSchema.pre(save)] There was an error processing the message image. [' + err + ']', { error: err });
      }
      
      if (filename) {
        message.image = filename;
        next();
      }
    })
  } else {
    next();
  }
});

MessageSchema.pre('save', function (next) {
  var message = this;
  
  if (message.image && typeof message.image === 'object') {
    Images.saveMessageImage(message.image, (err, filename) => {
      if (err) {
        Logger.error('[MessageSchema.pre(save)] There was an error processing the message image. [' + err + ']', { error: err });
      }
      
      if (filename) {
        message.image = filename;
        next();
      }
    })
  } else {
    next();
  }
});

const MessageModel = Mongoose.model('messages', MessageSchema);

module.exports = {
  schema: MessageSchema,
  model: MessageModel
};
