'use strict';

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

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _fs = require('fs');

var _fs2 = _interopRequireDefault(_fs);

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

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

var _imagemin = require('imagemin');

var _imagemin2 = _interopRequireDefault(_imagemin);

var _imageminJpegtran = require('imagemin-jpegtran');

var _imageminJpegtran2 = _interopRequireDefault(_imageminJpegtran);

var _imageminPngquant = require('imagemin-pngquant');

var _imageminPngquant2 = _interopRequireDefault(_imageminPngquant);

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var DEFAULT_CONFIG = {
  compressImages: false,
  compressionQuality: '70-85'
};

var OnDevice = function () {
  function OnDevice() {
    var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

    _classCallCheck(this, OnDevice);

    this.config = _extends({}, DEFAULT_CONFIG, config);
  }

  // helper


  _createClass(OnDevice, [{
    key: 'tempPath',
    value: function tempPath() {
      var dirPath = this.config.path;

      return _path2.default.join(dirPath, 'temp');
    }
  }, {
    key: 'ensureDirectories',
    value: function ensureDirectories() {
      var _config = this.config,
          dirPath = _config.path,
          compressImages = _config.compressImages;

      var tempPath = this.tempPath();

      if (!_fs2.default.existsSync(dirPath)) {
        _fs2.default.mkdirSync(dirPath);
      }

      if (compressImages) {
        if (!_fs2.default.existsSync(tempPath)) {
          _fs2.default.mkdirSync(tempPath);
        }
      }
    }

    // STORE

  }, {
    key: 'storeNormal',
    value: function storeNormal(file, filePath) {
      file.mv(filePath);
    }
  }, {
    key: 'storeAndCompress',
    value: function storeAndCompress(file, filePath) {
      var _this = this;

      var compressionQuality = this.config.compressionQuality;


      file.mv(filePath, function (err) {
        if (err) {
          (0, _nodeBits.logError)(err);
          return;
        }

        (0, _imagemin2.default)([filePath], _this.tempPath(), {
          plugins: [(0, _imageminJpegtran2.default)(), (0, _imageminPngquant2.default)({ quality: compressionQuality })]
        }).then(function (files) {
          _fs2.default.unlinkSync(filePath);
          _fs2.default.renameSync(files[0].path, filePath);
        });
      });
    }
  }, {
    key: 'store',
    value: function store(file) {
      var _config2 = this.config,
          dirPath = _config2.path,
          compressImages = _config2.compressImages;

      var filePath = _path2.default.join(dirPath, file.name);

      this.ensureDirectories();

      if (compressImages) {
        this.storeAndCompress(file, filePath);
      } else {
        this.storeNormal(file, filePath);
      }

      return filePath;
    }

    // GET

  }, {
    key: 'getImage',
    value: 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) {
        var filePath = item[field];
        if (!filePath) {
          res.send();
          return;
        }

        res.status(200).sendFile(filePath);
      }).catch(function (err) {
        (0, _nodeBits.logError)(err);
        res.status(500).send(err);
      });
    }
  }]);

  return OnDevice;
}();

exports.default = function (config) {
  return new OnDevice(config);
};