"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault")["default"];

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getRootFontSize = getRootFontSize;
exports.isCalcSize = isCalcSize;
exports.isPercentSize = isPercentSize;
exports.pxToPercent = pxToPercent;
exports.pxToRem = pxToRem;
exports.pxToVw = pxToVw;
exports.scaleSize = scaleSize;
exports.toPx = toPx;

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _isNumber = _interopRequireDefault(require("lodash/isNumber"));

var _isString = _interopRequireDefault(require("lodash/isString"));

var _isNil = _interopRequireDefault(require("lodash/isNil"));

var _round = _interopRequireDefault(require("lodash/round"));

var _cssUnitConverter = _interopRequireDefault(require("css-unit-converter"));

var _shared = require("choerodon-ui/shared");

var _math = _interopRequireDefault(require("choerodon-ui/dataset/math"));

function defaultTo(value, callback) {
  if ((0, _isNil["default"])(value)) {
    return callback();
  }

  return value;
}

function isEvalSupport() {
  var EVAL_SUPPORT = _shared.global.EVAL_SUPPORT;

  if (EVAL_SUPPORT === undefined) {
    try {
      /* eslint-disable-next-line no-eval */
      eval('');
      _shared.global.EVAL_SUPPORT = true;
      return true;
    } catch (e) {
      _shared.global.EVAL_SUPPORT = false;
      return false;
    }
  }

  return EVAL_SUPPORT;
}

function getRootFontSize() {
  var ROOT_STYLE = _shared.global.ROOT_STYLE;

  if (!ROOT_STYLE && typeof window !== 'undefined') {
    ROOT_STYLE = window.getComputedStyle(document.documentElement);
  }

  return ROOT_STYLE ? defaultTo(toPx(ROOT_STYLE.fontSize), function () {
    return 100;
  }) : 100;
}

function calculate(n1, n2, operation) {
  if (n1 !== undefined && n2 !== undefined) {
    switch (operation.trim()) {
      case '+':
        return n1 + n2;

      case '-':
        return n1 - n2;

      case '*':
        return n1 * n2;

      case '/':
        return n1 / n2;

      case '%':
        return n1 % n2;

      default:
        {
          if (isEvalSupport()) {
            /* eslint-disable-next-line no-eval */
            return eval("".concat(n1).concat(operation).concat(n2));
          }
        }
    }
  }
}

function scaleSize(px) {
  return px * getRootFontSize() / 100;
}

function pxToRem(num, useCurrentFrontSize) {
  if (num !== undefined && num !== null) {
    if (num === 0) {
      return '0';
    }

    if ((0, _isNumber["default"])(num)) {
      return "".concat(num / (useCurrentFrontSize ? getRootFontSize() : 100), "rem");
    }

    return num;
  }
}

function pxToVw(num) {
  var unit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'vw';

  if (num !== undefined && num !== null) {
    if ((0, _isNumber["default"])(num)) {
      var _document$documentEle = document.documentElement,
          clientWidth = _document$documentEle.clientWidth,
          clientHeight = _document$documentEle.clientHeight;
      return "".concat(num / (unit === 'vw' ? clientWidth : clientHeight) * 100).concat(unit);
    }

    return num;
  }
}

function pxToPercent(num, parentPx) {
  if (!(0, _isNil["default"])(num)) {
    num = _math["default"].floor(num);

    if (!(0, _isNil["default"])(parentPx)) {
      parentPx = _math["default"].floor(parentPx);
    }

    if ((0, _isNumber["default"])(num) && (0, _isNumber["default"])(parentPx)) {
      return "".concat((0, _round["default"])(num / parentPx, 6) * 100, "%");
    }

    return num;
  }
}

var builtInHeight = ['auto', 'fit-content', 'max-content', 'min-content', 'inherit', 'initial', 'unset', 'revert', 'available', '-webkit-fit-content', '-moz-max-content', '-moz-min-content', '-moz-initial'];
var calcReg = /^calc\(([^()]*)\)$/;
var unitReg = /^([+-]?[\d]+(?:[.][\d]+)?(?:[Ee][+-]?[\d]+)?)([^\d.+-]+)$/;

function isCalcSize(num) {
  return num.match(calcReg);
}

function isPercentSize(num) {
  return num.indexOf('%') !== -1;
}

function toPx(num, getRelationSize) {
  if (num !== undefined && num !== null) {
    if ((0, _isNumber["default"])(num)) {
      return num;
    }

    if ((0, _isString["default"])(num) && !builtInHeight.includes(num)) {
      var calcMatches = isCalcSize(num);

      if (calcMatches) {
        try {
          var list = calcMatches[1].split(' ');
          return list.slice(1).reduce(function (result, calc, index, array) {
            if (index % 2 === 1) {
              return calculate(result, toPx(calc, getRelationSize), array[index - 1]);
            }

            return result;
          }, toPx(list[0], getRelationSize));
        } catch (e) {
          console.error("Invalid property value in \"".concat(num, "\"."));
          return undefined;
        }
      }

      var unitMatches = num.match(unitReg);

      if (unitMatches) {
        var _unitMatches = (0, _slicedToArray2["default"])(unitMatches, 3),
            n = _unitMatches[1],
            u = _unitMatches[2];

        if (n) {
          var number = Number(n);

          if (u && u !== 'px') {
            switch (u) {
              case '%':
                {
                  var parentPx = getRelationSize && getRelationSize('%');

                  if (parentPx !== undefined) {
                    return parentPx * number / 100;
                  }

                  return undefined;
                }

              case 'vh':
                {
                  var viewHeight = defaultTo(getRelationSize && getRelationSize('vh'), function () {
                    return document.documentElement.clientHeight;
                  });
                  return viewHeight * number / 100;
                }

              case 'vw':
                {
                  var viewWidth = defaultTo(getRelationSize && getRelationSize('vw'), function () {
                    return document.documentElement.clientWidth;
                  });
                  return viewWidth * number / 100;
                }

              case 'rem':
                return number * getRootFontSize();

              case 'em':
                return number * defaultTo(getRelationSize && getRelationSize('em'), function () {
                  return defaultTo(toPx(window.getComputedStyle(document.body).fontSize), function () {
                    return 12;
                  });
                });

              default:
                try {
                  return (0, _cssUnitConverter["default"])(number, u, 'px');
                } catch (e) {
                  return undefined;
                }

            }
          }

          return number;
        }
      }
    }
  }
}
//# sourceMappingURL=UnitConvertor.js.map
