import take from "lodash-es/take";
import sortBy from "lodash-es/sortBy";
/* eslint-disable no-multi-assign */

export var componentToHex = function componentToHex(c) {
  var hex = c.toString(16);
  return hex.length === 1 ? "0".concat(hex) : hex;
};
export var getAverageHex = function getAverageHex(imgSrc) {
  return new Promise(function (resolve) {
    var imgEl = new Image();

    imgEl.onload = function () {
      var blockSize = 5; // only visit every 5 pixels

      var defaultHexs = ["#000", "#111", "#222", "#555", "#777", "#999", "#aaa", "#ccc", "#ddd", "#fff"]; // for non-supporting envs

      var canvas = document.createElement("canvas");
      var context = canvas.getContext && canvas.getContext("2d");
      var data = null;
      var i = -4;

      if (!context) {
        resolve(defaultHexs);
      }

      var height = canvas.height = imgEl.naturalHeight || imgEl.offsetHeight || imgEl.height;
      var width = canvas.width = imgEl.naturalWidth || imgEl.offsetWidth || imgEl.width;
      context.drawImage(imgEl, 0, 0);

      try {
        data = context.getImageData(0, 0, width, height);
      } catch (e) {
        /* security error, img on diff domain */
        resolve(defaultHexs);
      }

      var _data = data,
          length = _data.data.length;
      var colors = {};

      try {
        while (i < length) {
          var r = data.data[i];
          var g = data.data[i + 1];
          var b = data.data[i + 2];
          var a = data.data[i + 3]; // Clean transparent pixels

          if (a > 125 && r < 250 && g < 250 && b < 250) {
            var hex = "#".concat(componentToHex(r)).concat(componentToHex(g)).concat(componentToHex(b));

            if (colors[hex] !== undefined) {
              colors[hex]++;
            } else {
              colors[hex] = 1;
            }
          }

          i += blockSize * 4;
        }

        resolve(take(sortBy(Object.keys(colors), function (hex) {
          return -1 * colors[hex];
        }), 10));
      } catch (e) {
        resolve(defaultHexs);
      }
    };

    imgEl.src = imgSrc;
  });
};
export var isValidUrl = function isValidUrl(str) {
  var pattern = /^((http[s]*)?:\/\/)?((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|((\d{1,3}\.){3}\d{1,3}))(:\d+)?(\/[-a-z\d%_:.~+]*)*(\?[;&a-z\d%_.:~+=-]*)?(#[-a-z:\d_]*)?$/i;
  return pattern.test(str);
};
export var getImageDimensions = function getImageDimensions(file) {
  return new Promise(function (resolved) {
    var i = new Image();

    i.onload = function () {
      resolved({
        width: i.width,
        height: i.height
      });
    };

    i.src = file;
  });
};