"use strict";

var _crossFetch = _interopRequireWildcard(require("cross-fetch"));

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }

function _extends() { _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; }; return _extends.apply(this, arguments); }

var errors = require('./errors');

var FormData = require('form-data');

var utils = require('./utils');

var StreamImageStore = function StreamImageStore() {
  this.initialize.apply(this, arguments);
};

StreamImageStore.prototype = {
  initialize: function initialize(client, token) {
    this.client = client;
    this.token = token;
  },
  upload: function upload(uri, name) {
    var data = new FormData();
    var fileField;

    if (utils.isReadableStream(uri)) {
      fileField = uri;
    } else {
      fileField = {
        uri: uri,
        type: 'file',
        name: name || uri.split('/').reverse()[0]
      };
    }

    data.append('file', fileField);
    return (0, _crossFetch.default)("".concat(this.client.enrichUrl('images/'), "?api_key=").concat(this.client.apiKey), {
      method: 'post',
      body: data,
      headers: new _crossFetch.Headers({
        'Authorization': this.token
      })
    }).then(function (r) {
      return r.json();
    });
  },
  delete: function _delete(uri) {
    return this.client.delete({
      url: "images/".concat(uri),
      signature: this.token
    });
  },
  process: function process(uri, options) {
    var params = _extends(options);

    if (Array.isArray(params.crop)) {
      params.crop = params.crop.join(',');
    }

    return this.client.get({
      url: "images/".concat(uri),
      qs: params,
      signature: this.token
    });
  },
  thumbmail: function thumbmail(uri, w, h) {
    var _ref = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {
      crop: 'center',
      resize: 'clip'
    },
        crop = _ref.crop,
        resize = _ref.resize;

    return this.process(uri, {
      w: w,
      h: h,
      crop: crop,
      resize: resize
    });
  }
};
module.exports = StreamImageStore;