"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = require("react");
var _reactNative = require("react-native");
var _utils = require("../utils");
/**
 * Copyright (c) JOB TODAY S.A. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

const CACHE_SIZE = 50;
const imageDimensionsCache = (0, _utils.createCache)(CACHE_SIZE);
const useImageDimensions = image => {
  const [dimensions, setDimensions] = (0, _react.useState)(null);
  const getImageDimensions = image => {
    return new Promise(resolve => {
      if (typeof image === 'number') {
        const cacheKey = `${image}`;
        let imageDimensions = imageDimensionsCache.get(cacheKey);
        if (!imageDimensions) {
          const {
            width,
            height
          } = _reactNative.Image.resolveAssetSource(image);
          imageDimensions = {
            width,
            height
          };
          imageDimensionsCache.set(cacheKey, imageDimensions);
        }
        resolve(imageDimensions);
        return;
      }
      // @ts-ignore
      if (image.uri) {
        const source = image;
        const cacheKey = source.uri;
        const imageDimensions = imageDimensionsCache.get(cacheKey);
        if (imageDimensions) {
          resolve(imageDimensions);
        } else {
          // @ts-ignore
          _reactNative.Image.getSizeWithHeaders(source.uri, source.headers, (width, height) => {
            imageDimensionsCache.set(cacheKey, {
              width,
              height
            });
            resolve({
              width,
              height
            });
          }, () => {
            resolve({
              width: 0,
              height: 0
            });
          });
        }
      } else {
        resolve({
          width: 0,
          height: 0
        });
      }
    });
  };
  let isImageUnmounted = false;
  (0, _react.useEffect)(() => {
    getImageDimensions(image).then(dimensions => {
      if (!isImageUnmounted) {
        setDimensions(dimensions);
      }
    });
    return () => {
      isImageUnmounted = true;
    };
  }, [image]);
  return dimensions;
};
var _default = exports.default = useImageDimensions;
//# sourceMappingURL=useImageDimensions.js.map