const _ = require('lodash');


class Upload
{
  constructor(values)
  {
    var self = this;

    self.id = values.id || values._id || null;
    self.userId = values.userId || null;
    self.created = values.created || new Date();
    self.expiration = values.expiration || null;
    self.files = values.files || [];
  }
}


class UploadRepository
{
  constructor(store)
  {
    var self = this;
    self.store = store;
  }


  init()
  {
    var self = this;

    return new Promise((resolve, reject) =>
    {
      // Initialize database if empty
      self.store.count({}, (err, count) =>
      {
        if (err)
        {
          reject(err);
          return;
        }

        if (count == 0)
          self.addUser('admin', null, 'test', null);

        resolve();
      });
    });
  }


  addUpload(userId, files, expiration)
  {
    var self = this;

    return new Promise((resolve, reject) =>
    {
      var upload = {
        created: new Date(),
        userId: userId,
        expiration: expiration,
        files: _.map(_.filter(files,
                     (file) => file.hasOwnProperty('id') && file.hasOwnProperty('name')),
                     (file) => { return { id: file.id, name: file.name } })
      };

      if (upload.files.length)
      {
        self.store.insert(upload, (err, dbUpload) =>
        {
          if (err)
          {
            reject(err);
            return;
          }

          resolve(dbUpload._id);
        });
      }
      else
      {
        reject();
      }
    });
  }


  getUploads(userId)
  {
    var self = this;

    return new Promise((resolve, reject) =>
    {
      self.store.find(userId != null ? { userId: userId } : {}, (err, docs) =>
      {
        if (err)
        {
          reject(err);
          return;
        }

        resolve(docs.map((dbUpload) =>
        {
          return new Upload(dbUpload);
        }));
      });
    });
  }
}


module.exports = {
  UploadRepository
}