"use strict";

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

var _openDataPainter = _interopRequireDefault(require("./openDataPainter"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

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(_x, _x2, _x3, _x4, _x5, _x6, _x7) {
  return _drawTextMiddle.apply(this, arguments);
}

function _drawTextMiddle() {
  _drawTextMiddle = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(ctx, text, x, y, lineHeight, maxWidth, textAlign) {
    var lines;
    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            ctx.textBaseline = 'middle';

            if (maxWidth) {
              _context.next = 4;
              break;
            }

            ctx.fillText(text, x, y + lineHeight / 2);
            return _context.abrupt("return", y + lineHeight);

          case 4:
            _context.next = 6;
            return breakLinesForCanvas(ctx, text, maxWidth, lineHeight);

          case 6:
            lines = _context.sent;
            lines.forEach(function (l) {
              var width = l.width;
              var left = x;

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

              l.children.forEach(function (item) {
                if (typeof item == 'string') {
                  ctx.fillText(item, left, y + lineHeight / 2);
                  left += ctx.measureText(item).width;
                } else {
                  item.draw(ctx, left, y);
                  left += item.width;
                }
              });
              y += lineHeight;
            });
            return _context.abrupt("return", y);

          case 9:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));
  return _drawTextMiddle.apply(this, arguments);
}

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(_x8, _x9, _x10, _x11) {
  return _breakLinesForCanvas.apply(this, arguments);
}

function _breakLinesForCanvas() {
  _breakLinesForCanvas = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(ctx, text, width, lineHeight) {
    var reg, strReg, openDatas, matchStr, OpenDataCompoent, commonStrs, result, breakPoint, w, line, i, t, subText, openData;
    return regeneratorRuntime.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            reg = /\$(userName|departmentName)\=(.+?)\$(\s|$)/g;
            strReg = /\$(?:userName|departmentName)\=.+?\$(?:\s|$)/;
            openDatas = [];
            matchStr = reg.exec(text);

          case 4:
            if (!(matchStr != null)) {
              _context2.next = 12;
              break;
            }

            _context2.next = 7;
            return (0, _openDataPainter["default"])(ctx, {
              openId: matchStr[2],
              type: matchStr[1]
            }, lineHeight, width);

          case 7:
            OpenDataCompoent = _context2.sent;
            openDatas.push(OpenDataCompoent);
            matchStr = reg.exec(text);
            _context2.next = 4;
            break;

          case 12:
            commonStrs = text.split(strReg);
            result = [];
            breakPoint = 0;
            w = width;
            line = {
              width: 0,
              children: []
            };
            i = 0;

          case 18:
            if (!(i < commonStrs.length)) {
              _context2.next = 29;
              break;
            }

            t = commonStrs[i];

            while ((breakPoint = findBreakPoint(t, w, ctx)) !== -1) {
              subText = t.substring(0, breakPoint);
              line.children.push(subText);
              line.width += ctx.measureText(subText).width;
              t = t.substring(breakPoint);
              result.push(line);
              line = {
                width: 0,
                children: []
              };
              w = width;
            }

            if (t) {
              w = w - ctx.measureText(t).width;
              line.children.push(t);
              line.width += ctx.measureText(t).width;
            }

            openData = openDatas[i];

            if (openData) {
              _context2.next = 25;
              break;
            }

            return _context2.abrupt("continue", 26);

          case 25:
            if (w > openData.width) {
              line.children.push(openData);
              line.width += openData.width;
              w = w - openData.width;
            } else {
              if (line.width) {
                result.push(line);
                line = {
                  width: 0,
                  children: []
                };
              }

              line.children.push(openData);
              line.width += openData.width;
              w = width - openData.width;
            }

          case 26:
            i++;
            _context2.next = 18;
            break;

          case 29:
            if (line.width) result.push(line);
            return _context2.abrupt("return", result);

          case 31:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2);
  }));
  return _breakLinesForCanvas.apply(this, arguments);
}