var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.b64Digit = b64Digit;
exports.default = void 0;
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _CoreManager = _interopRequireDefault(require("./CoreManager"));
var _ParseError = _interopRequireDefault(require("./ParseError"));
var _Xhr = _interopRequireDefault(require("./Xhr.weapp"));
var XHR = null;
if (typeof XMLHttpRequest !== 'undefined') {
  XHR = XMLHttpRequest;
}
function b64Digit(number) {
  if (number < 26) {
    return String.fromCharCode(65 + number);
  }
  if (number < 52) {
    return String.fromCharCode(97 + (number - 26));
  }
  if (number < 62) {
    return String.fromCharCode(48 + (number - 52));
  }
  if (number === 62) {
    return '+';
  }
  if (number === 63) {
    return '/';
  }
  throw new TypeError('Tried to encode large digit ' + number + ' in base64.');
}
var ParseFile = function () {
  function ParseFile(name, data, type, metadata, tags) {
    (0, _classCallCheck2.default)(this, ParseFile);
    var specifiedType = type || '';
    this._name = name;
    this._metadata = metadata || {};
    this._tags = tags || {};
    if (data !== undefined) {
      if (Array.isArray(data) || data instanceof Uint8Array) {
        this._data = ParseFile.encodeBase64(data);
        this._source = {
          format: 'base64',
          base64: this._data,
          type: specifiedType
        };
      } else if (typeof Blob !== 'undefined' && data instanceof Blob) {
        this._source = {
          format: 'file',
          file: data,
          type: specifiedType
        };
      } else if (data && typeof data.uri === 'string' && data.uri !== undefined) {
        this._source = {
          format: 'uri',
          uri: data.uri,
          type: specifiedType
        };
      } else if (data && typeof data.base64 === 'string') {
        var base64 = data.base64.split(',').slice(-1)[0];
        var dataType = specifiedType || data.base64.split(';').slice(0, 1)[0].split(':').slice(1, 2)[0] || 'text/plain';
        this._data = base64;
        this._source = {
          format: 'base64',
          base64: base64,
          type: dataType
        };
      } else {
        throw new TypeError('Cannot create a Parse.File with that data.');
      }
    }
  }
  return (0, _createClass2.default)(ParseFile, [{
    key: "getData",
    value: function () {
      var _getData = (0, _asyncToGenerator2.default)(function* () {
        var _this = this;
        if (this._data) {
          return this._data;
        }
        if (!this._url) {
          throw new Error('Cannot retrieve data for unsaved ParseFile.');
        }
        var controller = _CoreManager.default.getFileController();
        var result = yield controller.download(this._url, {
          requestTask: function (task) {
            return _this._requestTask = task;
          }
        });
        this._data = result.base64;
        return this._data;
      });
      function getData() {
        return _getData.apply(this, arguments);
      }
      return getData;
    }()
  }, {
    key: "name",
    value: function () {
      return this._name;
    }
  }, {
    key: "url",
    value: function (options) {
      options = options || {};
      if (!this._url) {
        return;
      }
      if (options.forceSecure) {
        return this._url.replace(/^http:\/\//i, 'https://');
      } else {
        return this._url;
      }
    }
  }, {
    key: "metadata",
    value: function () {
      return this._metadata;
    }
  }, {
    key: "tags",
    value: function () {
      return this._tags;
    }
  }, {
    key: "save",
    value: function (options) {
      var _this2 = this;
      options = options || {};
      options.requestTask = function (task) {
        return _this2._requestTask = task;
      };
      options.metadata = this._metadata;
      options.tags = this._tags;
      var controller = _CoreManager.default.getFileController();
      if (!this._previousSave) {
        if (this._source.format === 'file') {
          this._previousSave = controller.saveFile(this._name, this._source, options).then(function (res) {
            _this2._name = res.name;
            _this2._url = res.url;
            _this2._data = null;
            _this2._requestTask = null;
            return _this2;
          });
        } else if (this._source.format === 'uri') {
          this._previousSave = controller.download(this._source.uri, options).then(function (result) {
            if (!(result && result.base64)) {
              return {};
            }
            var newSource = {
              format: 'base64',
              base64: result.base64,
              type: result.contentType
            };
            _this2._data = result.base64;
            _this2._requestTask = null;
            return controller.saveBase64(_this2._name, newSource, options);
          }).then(function (res) {
            _this2._name = res.name;
            _this2._url = res.url;
            _this2._requestTask = null;
            return _this2;
          });
        } else {
          this._previousSave = controller.saveBase64(this._name, this._source, options).then(function (res) {
            _this2._name = res.name;
            _this2._url = res.url;
            _this2._requestTask = null;
            return _this2;
          });
        }
      }
      if (this._previousSave) {
        return this._previousSave;
      }
    }
  }, {
    key: "cancel",
    value: function () {
      if (this._requestTask && typeof this._requestTask.abort === 'function') {
        this._requestTask._aborted = true;
        this._requestTask.abort();
      }
      this._requestTask = null;
    }
  }, {
    key: "destroy",
    value: function () {
      var _this3 = this;
      var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      if (!this._name) {
        throw new _ParseError.default(_ParseError.default.FILE_DELETE_UNNAMED_ERROR, 'Cannot delete an unnamed file.');
      }
      var destroyOptions = {
        useMasterKey: true
      };
      if (Object.hasOwn(options, 'useMasterKey')) {
        destroyOptions.useMasterKey = !!options.useMasterKey;
      }
      var controller = _CoreManager.default.getFileController();
      return controller.deleteFile(this._name, destroyOptions).then(function () {
        _this3._data = undefined;
        _this3._requestTask = null;
        return _this3;
      });
    }
  }, {
    key: "toJSON",
    value: function () {
      return {
        __type: 'File',
        name: this._name,
        url: this._url
      };
    }
  }, {
    key: "equals",
    value: function (other) {
      if (this === other) {
        return true;
      }
      return other instanceof ParseFile && this.name() === other.name() && this.url() === other.url() && typeof this.url() !== 'undefined';
    }
  }, {
    key: "setMetadata",
    value: function (metadata) {
      var _this4 = this;
      if (metadata && typeof metadata === 'object') {
        Object.keys(metadata).forEach(function (key) {
          _this4.addMetadata(key, metadata[key]);
        });
      }
    }
  }, {
    key: "addMetadata",
    value: function (key, value) {
      if (typeof key === 'string') {
        this._metadata[key] = value;
      }
    }
  }, {
    key: "setTags",
    value: function (tags) {
      var _this5 = this;
      if (tags && typeof tags === 'object') {
        Object.keys(tags).forEach(function (key) {
          _this5.addTag(key, tags[key]);
        });
      }
    }
  }, {
    key: "addTag",
    value: function (key, value) {
      if (typeof key === 'string') {
        this._tags[key] = value;
      }
    }
  }], [{
    key: "fromJSON",
    value: function (obj) {
      if (obj.__type !== 'File') {
        throw new TypeError('JSON object does not represent a ParseFile');
      }
      var file = new ParseFile(obj.name);
      file._url = obj.url;
      return file;
    }
  }, {
    key: "encodeBase64",
    value: function (bytes) {
      var chunks = [];
      chunks.length = Math.ceil(bytes.length / 3);
      for (var i = 0; i < chunks.length; i++) {
        var b1 = bytes[i * 3];
        var b2 = bytes[i * 3 + 1] || 0;
        var b3 = bytes[i * 3 + 2] || 0;
        var has2 = i * 3 + 1 < bytes.length;
        var has3 = i * 3 + 2 < bytes.length;
        chunks[i] = [b64Digit(b1 >> 2 & 0x3f), b64Digit(b1 << 4 & 0x30 | b2 >> 4 & 0x0f), has2 ? b64Digit(b2 << 2 & 0x3c | b3 >> 6 & 0x03) : '=', has3 ? b64Digit(b3 & 0x3f) : '='].join('');
      }
      return chunks.join('');
    }
  }]);
}();
var DefaultController = {
  saveFile: function () {
    var _saveFile = (0, _asyncToGenerator2.default)(function* (name, source, options) {
      if (source.format !== 'file') {
        throw new Error('saveFile can only be used with File-type sources.');
      }
      var base64Data = yield new Promise(function (res, rej) {
        var reader = new FileReader();
        reader.onload = function () {
          return res(reader.result);
        };
        reader.onerror = function (error) {
          return rej(error);
        };
        reader.readAsDataURL(source.file);
      });
      var _base64Data$split = base64Data.split(','),
        _base64Data$split2 = (0, _slicedToArray2.default)(_base64Data$split, 2),
        first = _base64Data$split2[0],
        second = _base64Data$split2[1];
      var data = second ? second : first;
      var newSource = {
        format: 'base64',
        base64: data,
        type: source.type || (source.file ? source.file.type : undefined)
      };
      return yield DefaultController.saveBase64(name, newSource, options);
    });
    function saveFile() {
      return _saveFile.apply(this, arguments);
    }
    return saveFile;
  }(),
  saveBase64: function (name, source) {
    var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    if (source.format !== 'base64') {
      throw new Error('saveBase64 can only be used with Base64-type sources.');
    }
    var data = {
      base64: source.base64,
      fileData: {
        metadata: Object.assign({}, options.metadata),
        tags: Object.assign({}, options.tags)
      }
    };
    delete options.metadata;
    delete options.tags;
    if (source.type) {
      data._ContentType = source.type;
    }
    return _CoreManager.default.getRESTController().request('POST', 'files/' + name, data, options);
  },
  download: function (uri, options) {
    if (XHR) {
      return this.downloadAjax(uri, options);
    } else {
      return Promise.reject('Cannot make a request: No definition of XMLHttpRequest was found.');
    }
  },
  downloadAjax: function (uri, options) {
    return new Promise(function (resolve, reject) {
      var xhr = new XHR();
      xhr.open('GET', uri, true);
      xhr.responseType = 'arraybuffer';
      xhr.onerror = function (e) {
        reject(e);
      };
      xhr.onreadystatechange = function () {
        if (xhr.readyState !== xhr.DONE) {
          return;
        }
        if (!this.response) {
          return resolve({});
        }
        var bytes = new Uint8Array(this.response);
        resolve({
          base64: ParseFile.encodeBase64(bytes),
          contentType: xhr.getResponseHeader('content-type')
        });
      };
      options.requestTask(xhr);
      xhr.send();
    });
  },
  deleteFile: function (name, options) {
    var headers = {
      'X-Parse-Application-ID': _CoreManager.default.get('APPLICATION_ID')
    };
    if (options.useMasterKey) {
      headers['X-Parse-Master-Key'] = _CoreManager.default.get('MASTER_KEY');
    }
    var url = _CoreManager.default.get('SERVER_URL');
    if (url[url.length - 1] !== '/') {
      url += '/';
    }
    url += 'files/' + name;
    return _CoreManager.default.getRESTController().ajax('DELETE', url, '', headers).catch(function (response) {
      if (!response || response === 'SyntaxError: Unexpected end of JSON input') {
        return Promise.resolve();
      } else {
        return _CoreManager.default.getRESTController().handleError(response);
      }
    });
  },
  _setXHR: function (xhr) {
    XHR = xhr;
  },
  _getXHR: function () {
    return XHR;
  }
};
_CoreManager.default.setFileController(DefaultController);
var _default = exports.default = ParseFile;