const mongodb = require('mongodb');
const getDb = require('../util/database').getDb;
const ObjectId = mongodb.ObjectId; // needed?

class User {
  constructor(email, password) { // removed , id
    this.email = email;
    this.password = password;
    //this._id = id;
  }

  save() {
    const db = getDb();
    return db.collection('users').insertOne(this)
      .then(result => {
        console.log('save() result: ', result);
        return result;
      })
      .catch(err => {
        console.log('error: ', err)
      });
  }

  static findById(userId) {
    const db = getDb();
    return db
      .collection('users')
      .findOne({
        _id: new ObjectId(userId)
      })
      .then(user => {
        console.log(user);
        return user;
      })
      .catch(err => {
        console.log(err);
      });
  }

  static findByEm(em) {
    const db = getDb();
    return db.collection('users')
      .find({
        'email': em
      })
      .next()
      .then(user => {
        console.log('user find test: ', user)
        return user;
      }).catch(err => {
        console.log('error: ', err)
      });
  }
}

module.exports = User;