import { MAX_COLOR_ALPHA } from './consts.js';
import { hsl2rgb } from './hsl2rgb.js';

function cssColor(color) {
  if (!color) {
    return void 0;
  }
  var easyColor = _rgba(color) || _hex6(color) || _hex3(color) || _hsla(color);
  if (easyColor) {
    return easyColor;
  }
  return _browserCompute(color);
}
function _browserCompute(str) {
  if (typeof document === "undefined") {
    return void 0;
  }
  var elem = document.createElement("div");
  elem.style.backgroundColor = str;
  elem.style.position = "absolute";
  elem.style.top = "-9999px";
  elem.style.left = "-9999px";
  elem.style.height = "1px";
  elem.style.width = "1px";
  document.body.appendChild(elem);
  var eComputedStyle = getComputedStyle(elem);
  var computedColor = eComputedStyle && eComputedStyle.backgroundColor;
  document.body.removeChild(elem);
  if (computedColor === "rgba(0, 0, 0, 0)" || computedColor === "transparent") {
    switch (str.trim()) {
      case "transparent":
      case "#0000":
      case "#00000000":
        return { r: 0, g: 0, b: 0, a: 0 };
    }
    return void 0;
  }
  return _rgba(computedColor);
}
function _rgba(str) {
  if (!str) {
    return void 0;
  }
  var match = str.match(/^rgb(a?)\(([\d., ]+)\)$/);
  if (match) {
    var hasAlpha = !!match[1];
    var expectedPartCount = hasAlpha ? 4 : 3;
    var parts = match[2].split(/ *, */).map(Number);
    if (parts.length === expectedPartCount) {
      return {
        r: parts[0],
        g: parts[1],
        b: parts[2],
        a: hasAlpha ? parts[3] * 100 : MAX_COLOR_ALPHA
      };
    }
  }
}
function _hsla(str) {
  var match = str.match(/^hsl(a?)\(([\d., ]+)\)$/);
  if (match) {
    var hasAlpha = !!match[1];
    var expectedPartCount = hasAlpha ? 4 : 3;
    var parts = match[2].split(/ *, */).map(Number);
    if (parts.length === expectedPartCount) {
      var rgba = hsl2rgb(parts[0], parts[1], parts[2]);
      rgba.a = hasAlpha ? parts[3] * 100 : MAX_COLOR_ALPHA;
      return rgba;
    }
  }
}
function _hex6(str) {
  if (str[0] === "#" && str.length === 7 && /^#[\da-fA-F]{6}$/.test(str)) {
    return {
      r: parseInt(str.slice(1, 3), 16),
      g: parseInt(str.slice(3, 5), 16),
      b: parseInt(str.slice(5, 7), 16),
      a: MAX_COLOR_ALPHA
    };
  }
}
function _hex3(str) {
  if (str[0] === "#" && str.length === 4 && /^#[\da-fA-F]{3}$/.test(str)) {
    return {
      r: parseInt(str[1] + str[1], 16),
      g: parseInt(str[2] + str[2], 16),
      b: parseInt(str[3] + str[3], 16),
      a: MAX_COLOR_ALPHA
    };
  }
}

export { cssColor };
