import { startsWithOneOf } from "../../utils";
export function clamp(val, max) {
  if (max === void 0) {
    max = 1;
  }
  return Math.min(max, Math.max(0, val));
}
export function integerFromPercent(n, size) {
  return Math.round(parseFloat(n) * size / 100);
}
export function floatFromPercent(n) {
  return parseFloat((parseFloat(n) / 100).toFixed(5));
}
export function roundToPrecision(n, precision) {
  if (precision === void 0) {
    precision = 2;
  }
  return parseFloat(n.toFixed(precision));
}
export function extractColorParts(input, regex) {
  var parts = regex.exec(input);
  if (!parts) {
    throw new Error(input + " does not match color patterns: [\n      " + regex + "\n    ]");
  }
  return parts;
}
export function parseRGBParts(parts) {
  var r = parseToInteger(parts[1], 255);
  var g = parseToInteger(parts[2], 255);
  var b = parseToInteger(parts[3], 255);
  var a = parts[4] ? parseToFloat(parts[4]) : 1.0;
  if (isNaN(r)) {
    throw new Error("Could not parse red=" + parts[1] + " to number");
  }
  if (isNaN(g)) {
    throw new Error("Could not parse green=" + parts[2] + " to number");
  }
  if (isNaN(b)) {
    throw new Error("Could not parse blue=" + parts[3] + " to number");
  }
  if (isNaN(a)) {
    throw new Error("Could not parse alpha=" + parts[4] + " to number");
  }
  return {
    r: r,
    g: g,
    b: b,
    a: a
  };
}
export function parseHSLParts(parts) {
  var h = parseInt(parts[1], 10);
  var s = parseToFloat(parts[2]);
  var l = parseToFloat(parts[3]);
  var a = parts[4] ? parseToFloat(parts[4]) : 1.0;
  if (isNaN(h)) {
    throw new Error("Could not parse hue=" + parts[1] + " to number");
  } else if (isNaN(s)) {
    throw new Error("Could not parse saturation=" + parts[2] + " to number");
  } else if (isNaN(l)) {
    throw new Error("Could not parse lightness=" + parts[3] + " to number");
  } else if (isNaN(a)) {
    throw new Error("Could not parse alpha=" + parts[4] + " to number");
  }
  return {
    h: h,
    s: s,
    l: l,
    a: a
  };
}
export function parseToInteger(part, size) {
  return part.endsWith('%') ? integerFromPercent(part, size) : parseInt(part, 10);
}
export function parseToFloat(part) {
  return part.endsWith('%') ? floatFromPercent(part) : parseFloat(part);
}
var calculateHue = function calculateHue(hue) {
  if (hue < 0) {
    return hue + 1;
  }
  if (hue > 1) {
    return hue - 1;
  }
  return hue;
};
export function hue2rgb(hue, t1, t2) {
  var calculatedHue = calculateHue(hue);
  if (calculatedHue < 1 / 6) {
    return t2 + (t1 - t2) * 6 * calculatedHue;
  }
  if (calculatedHue < 1 / 2) {
    return t1;
  }
  if (calculatedHue < 2 / 3) {
    return t2 + (t1 - t2) * (2 / 3 - calculatedHue) * 6;
  }
  return t2;
}
export var isColor = function isColor(input) {
  var colorStarters = ['#', 'rgb', 'hsl'];
  if (input) {
    return startsWithOneOf(colorStarters, input);
  }
  return false;
};