"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.changeAlpha = changeAlpha;
exports.combineColors = combineColors;
exports.getValidColor = getValidColor;
exports.hasEnoughContrast = hasEnoughContrast;
exports.isSameColor = isSameColor;
exports.toHex = toHex;
var _chromaJs = _interopRequireDefault(require("chroma-js"));
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

function getValidColor(color) {
  try {
    return (0, _chromaJs.default)(color);
  } catch {
    return (0, _chromaJs.default)('red');
  }
}
function hasEnoughContrast(color, isDark, threshold = 4.5) {
  return _chromaJs.default.contrast(getValidColor(color), isDark ? 'black' : 'white') >= threshold;
}
function changeAlpha(color, alpha) {
  const [r, g, b] = getValidColor(color).rgb();
  return `rgba(${r},${g},${b},${alpha})`;
}
function toHex(color) {
  return getValidColor(color).hex().toLowerCase();
}
function isSameColor(color1, color2) {
  return toHex(color1) === toHex(color2);
}

/**
 * Blend a foreground (fg) color with a background (bg) color
 */
function combineColors(fg, bg) {
  const [fgR, fgG, fgB, fgA] = getValidColor(fg).rgba();
  const [bgR, bgG, bgB, bgA] = getValidColor(bg).rgba();

  // combine colors only if foreground has transparency
  if (fgA === 1) {
    return _chromaJs.default.rgb(fgR, fgG, fgB).hex();
  }

  // For reference on alpha calculations:
  // https://en.wikipedia.org/wiki/Alpha_compositing
  const alpha = fgA + bgA * (1 - fgA);
  if (alpha === 0) {
    return '#00000000';
  }
  const r = Math.round((fgR * fgA + bgR * bgA * (1 - fgA)) / alpha);
  const g = Math.round((fgG * fgA + bgG * bgA * (1 - fgA)) / alpha);
  const b = Math.round((fgB * fgA + bgB * bgA * (1 - fgA)) / alpha);
  return `rgba(${r}, ${g}, ${b}, ${alpha})`;
}