//const debug = require('debug')('recv:users');
const _ = require('lodash');
const path = require('path');
const mkdirp = require('mkdirp');
const Datastore = require('nedb');
const shortid = require('shortid');
const retry = require('async-retry');

const UserRepository = require('./user').UserRepository;
const CodeRepository = require('./code').CodeRepository;
const UploadRepository = require('./upload').UploadRepository;


class Repository
{
  constructor(config)
  {
    var self = this;
    self.config = config;
  }


  load()
  {
    var self = this;

    return new Promise((resolve, reject) =>
    {
      const initStore = (filename) =>
      {
        var store = new Datastore({
          filename: path.join(self.config.path, filename),
          autoload: true
        });

        store.persistence.setAutocompactionInterval(self.config.autocompactionInterval);
        return store;
      };

      mkdirp(self.config.path, (err) =>
      {
        if (err)
        {
          reject(err);
          return;
        }

        self.users = new UserRepository(initStore('user.db'));
        self.codes = new CodeRepository(initStore('code.db'));
        self.uploads = new UploadRepository(initStore('upload.db'));

        self.users.init()
          .then(() => { resolve() })
          .catch((e) => { reject(e); });
      });
    });
  }
}


module.exports = Repository;