"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.breakLinesForCanvas = breakLinesForCanvas;
exports.drawImage = drawImage;
exports.drawTextMiddle = drawTextMiddle;

function drawImage(ctx, url, x, y, width, height) {
  return new Promise(function (res) {
    var img = new Image();
    img.src = url;

    img.onload = function () {
      ctx.drawImage(img, x, y, width, height);
      res();
    };
  });
}

function drawTextMiddle(ctx, text, x, y, lineHeight, maxWidth, textAlign) {
  ctx.textBaseline = "middle";

  if (!maxWidth) {
    ctx.fillText(text, x, y + lineHeight / 2);
    return y + lineHeight;
  }

  var lines = breakLinesForCanvas(ctx, text, maxWidth);
  lines.forEach(function (l) {
    var _ctx$measureText = ctx.measureText(l),
        width = _ctx$measureText.width;

    var left = x;

    if (textAlign == "center" && maxWidth) {
      console.log(maxWidth, width);
      left = (maxWidth - width) / 2 + x;
    }

    ctx.fillText(l, left, y + lineHeight / 2);
    y += lineHeight;
  });
  return y;
}

function findBreakPoint(text, width, context) {
  var min = 0;
  var max = text.length - 1;

  while (min <= max) {
    var middle = Math.floor((min + max) / 2);
    var middleWidth = context.measureText(text.substr(0, middle)).width;
    var oneCharWiderThanMiddleWidth = context.measureText(text.substr(0, middle + 1)).width;

    if (middleWidth <= width && oneCharWiderThanMiddleWidth > width) {
      return middle;
    }

    if (middleWidth < width) {
      min = middle + 1;
    } else {
      max = middle - 1;
    }
  }

  return -1;
}

function breakLinesForCanvas(ctx, text, width) {
  var result = [];
  var breakPoint = 0;

  while ((breakPoint = findBreakPoint(text, width, ctx)) !== -1) {
    result.push(text.substr(0, breakPoint));
    text = text.substr(breakPoint);
  }

  if (text) {
    result.push(text);
  }

  return result;
}