'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _imgur = require('imgur');

var _imgur2 = _interopRequireDefault(_imgur);

var _nodeBits = require('node-bits');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var defaultUrl = 'https://api.imgur.com/3/';

exports.default = function (config) {
  return {
    store: function store(file) {
      var base64 = file.data.toString('base64');

      // upload image
      _imgur2.default.setClientId(config.clientId);
      _imgur2.default.setAPIUrl(config.apiUrl || defaultUrl);

      return _imgur2.default.uploadBase64(base64).then(function (json) {
        return json.data.link;
      });
    },

    getImage: function getImage(req, res, db) {
      var model = req.query.model;
      if (!model) {
        res.status(404).send('You must provide model for this configuration.');
        return;
      }

      var field = req.query.field;
      if (!field) {
        res.status(404).send('You must provide field for this configuration.');
        return;
      }

      var id = req.query.id;
      if (!id) {
        res.status(404).send('You must provide id for this configuration.');
        return;
      }

      db.findById(model, id).then(function (item) {
        res.redirect(item[field]);
      }).catch(function (err) {
        (0, _nodeBits.logError)(err);
        res.status(500).send(err);
      });
    }
  };
};