import _ from "lodash";
import moment from "moment";
import { stringActions } from "../../apis";
import detectFaces from "./detectFaces";
import getScaledOffset from "./getScaledOffset";
const findLandmarkRange = async (url, options) => {
  let cachedValues;
  if (options && options.cachedValues) {
    cachedValues = options.cachedValues;
  }
  try {
    const response = await stringActions.getString("plussSpace", `imagefaces_${encodeURIComponent(url)}`);
    cachedValues = response.data;
  } catch (e) {
    console.log("errored from cache");
  }
  if (!cachedValues || !cachedValues.faces || !cachedValues.image || _.isEmpty(cachedValues.faces) && moment().add(-1, "w").valueOf() > moment(cachedValues.timestamp).valueOf()) {
    cachedValues = await detectFaces(url);
  }
  const {
    faces,
    image
  } = cachedValues;
  let landmarkStartX = null;
  let landmarkStartY = null;
  let landmarkEndX = null;
  let landmarkEndY = null;
  if (_.isEmpty(faces)) {
    landmarkStartX = image.width / 2;
    landmarkStartY = image.height / 2;
    landmarkEndX = image.width / 2;
    landmarkEndY = image.height / 2;
  } else {
    faces.forEach(face => {
      const {
        bounds
      } = face;
      if (!landmarkStartX || bounds.origin.x < landmarkStartX) {
        landmarkStartX = bounds.origin.x;
      }
      if (!landmarkStartY || bounds.origin.y < landmarkStartY) {
        landmarkStartY = bounds.origin.y;
      }
      const faceEndX = bounds.origin.x + bounds.size.width;
      if (!landmarkEndX || faceEndX > landmarkEndX) {
        landmarkEndX = faceEndX;
      }
      const faceEndY = bounds.origin.y + bounds.size.height;
      if (!landmarkEndY || faceEndX > landmarkEndY) {
        landmarkEndY = faceEndY;
      }
    });
  }
  let targetWidth = image.width;
  let targetHeight = image.height;
  if (options && options.targetWidth && options.targetHeight) {
    const {
      scaleFactor
    } = getScaledOffset(image.width, image.height, options.targetWidth, options.targetHeight);
    landmarkStartX *= scaleFactor;
    landmarkStartY *= scaleFactor;
    landmarkEndX *= scaleFactor;
    landmarkEndY *= scaleFactor;
    targetWidth = options.targetWidth;
    targetHeight = options.targetHeight;
  }
  if (landmarkStartX < 0) {
    landmarkStartX = 0;
  }
  if (landmarkStartY < 0) {
    landmarkStartY = 0;
  }
  if (landmarkEndX > targetWidth) {
    landmarkEndX = targetWidth;
  }
  if (landmarkEndY > targetHeight) {
    landmarkEndY = targetHeight;
  }
  return {
    start: {
      x: landmarkStartX,
      y: landmarkStartY
    },
    end: {
      x: landmarkEndX,
      y: landmarkEndY
    },
    height: image.height,
    width: image.width
  };
};
export default findLandmarkRange;
//# sourceMappingURL=findLandmarkRange.js.map