"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.disableSpinnerRepeat = disableSpinnerRepeat;
exports.fixVolumeSize = fixVolumeSize;
exports.getBoxSize = getBoxSize;
exports.noInternet = noInternet;
exports.parseH5jAttrs = parseH5jAttrs;
exports.surfaceAlignmentFactors = surfaceAlignmentFactors;
exports.textFromFileOrURL = textFromFileOrURL;

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function disableSpinnerRepeat(event, previous) {
  // If the change from the previous value...
  var change = Math.abs(event.target.valueAsNumber - previous); // ...looks like the "step" amount specified by the spinner
  // (the little up and down arrows)...

  var isStep = Math.abs(change - event.target.step) < 0.0001;

  if (isStep) {
    // ...then take away focus, so the spinner button works only once.
    // This approach works better than traditional throttling or
    // debouncing, and (mostly) does not affect the direct typing of
    // a numeric value.
    event.target.blur();
  }
}

function fixVolumeSize(volumeSize, data) {
  var volumeSizeFixed = volumeSize; // TODO: Is it really right that in practice, `image_size[2]` on the original file can be wrong?

  var realFrameCount = data.byteLength / (volumeSize[0] * volumeSize[1]);

  if (realFrameCount !== volumeSize[2]) {
    console.log("Frame count (z) seems to be ".concat(realFrameCount, " rather than ").concat(volumeSize[2]));
    volumeSizeFixed[2] = realFrameCount;
  }

  return volumeSizeFixed;
}

function getBoxSize(volSize, voxelSize) {
  var physicalSize = volSize.map(function (e, i) {
    return e * voxelSize[i];
  });
  var sizeMax = Math.max.apply(Math, _toConsumableArray(physicalSize));
  var boxSize = physicalSize.map(function (e) {
    return e / sizeMax;
  });
  return boxSize;
}

function noInternet(error) {
  return error instanceof TypeError && error.message === 'Failed to fetch';
} // In the result object:
// `voxSize` is the `voxel_size` attribute from the H5J file (HDF5 container)
// `volSize` is the `image_size` attribute
// `chanSpecs` is the `channel_spec` attributes


function parseH5jAttrs(attrs) {
  var volSize = [0, 0, 0];
  var voxSize = [0, 0, 0];

  if ('image_size' in attrs) {
    volSize = attrs.image_size;
    console.log("Attribute 'image_size': ".concat(volSize));
  }

  if ('voxel_size' in attrs) {
    voxSize = attrs.voxel_size;
    console.log("Attribute 'voxel_size': ".concat(voxSize));
  }

  var attrsChs = attrs.channels;

  if ('width' in attrs.channels) {
    var widths = attrsChs.width;
    var width = widths[0];
    volSize[0] = width;
  }

  if ('height' in attrs.channels) {
    var heights = attrsChs.height;
    var height = heights[0];
    volSize[1] = height;
  }

  if ('frames' in attrs.channels) {
    var frameses = attrsChs.frames;
    var frames = frameses[0];
    volSize[2] = frames;
  }

  var alignment = 8;
  volSize[0] = Math.ceil(volSize[0] / alignment) * alignment;
  volSize[1] = Math.ceil(volSize[1] / alignment) * alignment;
  console.log("Word aligned volume size: ".concat(volSize));
  var chanSpecs = attrs.channels.names.map(function (name, i) {
    return {
      name: name,
      content: attrs.channels.content_types[i]
    };
  });
  return {
    volSize: volSize,
    voxSize: voxSize,
    chanSpecs: chanSpecs
  };
} // Returns the scale and translation needed to align a surface in micron coordinates
// with the volume having the specified volume size (number of voxels per dimension)
// and voxel size (microns per voxel per dimension).


function surfaceAlignmentFactors(units, volSize, voxelSize) {
  var surfaceScale = 0.00161;
  var surfaceTranslation = [-313.7, -147.5, -86.5];

  if (units === 'micron') {
    var micronSize = volSize.map(function (e, i) {
      return e * voxelSize[i];
    });
    var sizeMax = Math.max.apply(Math, _toConsumableArray(micronSize));
    surfaceScale = sizeMax > 0 ? 1 / sizeMax : 1;
    surfaceTranslation = micronSize.map(function (e) {
      return -e / 2;
    });
  }

  return {
    surfaceScale: surfaceScale,
    surfaceTranslation: surfaceTranslation
  };
}

function textFromFileOrURL(_x) {
  return _textFromFileOrURL.apply(this, arguments);
}

function _textFromFileOrURL() {
  _textFromFileOrURL = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(src) {
    var errPrefix;
    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            errPrefix = "textFromFileOrURL failed:"; // Treat a string argument as a URL and use `fetch` to return a promise that 
            // resolves to the text.

            if (!(typeof src === 'string')) {
              _context.next = 3;
              break;
            }

            return _context.abrupt("return", fetch(src).then(function (response) {
              if (response.ok) {
                if (response.status === 200) {
                  return response.text();
                }

                throw new Error("".concat(errPrefix, " response.status ").concat(response.status, ", \"").concat(response.statusText, "\""));
              }

              throw new Error("".concat(errPrefix, " response.ok false"));
            }));

          case 3:
            if (!(src instanceof File)) {
              _context.next = 5;
              break;
            }

            return _context.abrupt("return", new Promise(function (resolve, reject) {
              var reader = new FileReader();

              reader.onload = function (readerEvent) {
                try {
                  var text = readerEvent.target.result;
                  resolve(text);
                } catch (exc) {
                  reject(new Error("".concat(errPrefix, " ").concat(exc)));
                }
              };

              reader.onerror = reject;
              reader.readAsText(src);
            }));

          case 5:
            return _context.abrupt("return", Promise.reject(new Error("".concat(errPrefix, " unknown \"src\" type"))));

          case 6:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));
  return _textFromFileOrURL.apply(this, arguments);
}