function randomColor(alpha) {
  var alpha = alpha || 0.5;
  var r = Math.round(Math.random() * 255);
  var g = Math.round(Math.random() * 255);
  var b = Math.round(Math.random() * 255);
  return 'rgba(' + [r, g, b, alpha].join(',') + ')';
}

function isFunction(functionToCheck) {
  return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
}

var canvas = document.createElement('canvas');
canvas.width = canvas.height = 1;
var ctx = canvas.getContext('2d');



export default class Utils {

  /**
   * Parse color to rgba.
   */
  static parseColor(color) {
    ctx.fillStyle = color;
    ctx.fillRect(0, 0, 1, 1);
    let pixel = ctx.getImageData(0, 0, 1, 1);
    return pixel.data;
  }

  /**
   * Return rgb color by the given [r,g,b,a]
   */
  static makeColorRgba(buf) : string {
    return 'rgba(' + buf[0] + ',' + buf[1] + ',' + buf[2] + ',' + buf[3] / 255 + ')';
  }

  /**
   * Return hex color by the given [r,g,b,a]
   */
  static makeColorHex(buf) {
    let r = ('00' + buf[0].toString(16)).slice(-2);
    let g = ('00' + buf[1].toString(16)).slice(-2);
    let b = ('00' + buf[2].toString(16)).slice(-2);
    return `#${r}${g}${b}`;
  }

  static makeColor(buf) : string {
    return this.makeColorRgba(buf);
  }

  /**
   * Change the give color alpha.
   */
  static setAlpha(color, alpha) {
    var buf = this.parseColor(color);
    buf[3] = alpha;
    return this.makeColor(buf);
  }




  /**
   * Promis load file as array buffer.
   */
  static loadFile(file) {
    return new Promise(function (done, reject) {
      var reader = new FileReader();
      reader.onload = function () {
        done(reader.result);
      }
      reader.onerror = reject;
      reader.readAsArrayBuffer(file);
    });
  }


  /**
   * Request binary data
   */
  static ajaxBinary(url) {
    return new Promise(function (done, reject) {
      var oReq = new XMLHttpRequest();
      oReq.open("GET", url, true);
      oReq.responseType = "arraybuffer";
      oReq.onload = function (oEvent) {
        var arrayBuffer = oReq.response; // Note: not oReq.responseText
        if (arrayBuffer) {
          //var byteArray = new Uint8Array(arrayBuffer);
          done(arrayBuffer);
        } else {
          reject('Empty response');
        }
      };
      oReq.onerror = reject;
      oReq.send(null);
    });
  }




}

export {
  randomColor,
  isFunction,
}
