function toLower(v) {
return v.toLowerCase();
}

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;

const db = mongoose.connect('mongodb://localhost:27017/contact-manager');

// Define a contact Schema
const contactSchema = mongoose.Schema({
  fname: { type: String, set: toLower },
  lname: { type: String, set: toLower },
  phone: { type: String, set: toLower },
  email: { type: String, set: toLower }
});

const Contact = mongoose.model('Contact', contactSchema);

const addContact = (contact) => {
  console.info(`กำลังเพิ่มรายการติดต่อ ${contact}`);
  Contact.create(contact, (err) => {
    console.info('เพิ่มรายการติดต่อใหม่ สำเร็จ');
    db.disconnect();
  });
};

const getContact = (name) => {
  const search = new RegExp(name, 'i');
  Contact.find({$or: [{fname: search }, {lname: search }]})
  .exec((err, contact) => {
    console.info(contact);
    console.info(`ค้นเจอทั้งหมด ${contact.length} รายการ`);
    db.disconnect();
  });
};

//exports.toLower = lo
module.exports = {  addContact, getContact };
