'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _warning = require('fbjs/lib/warning');

var _warning2 = _interopRequireDefault(_warning);

var _Base2 = require('./Base');

var _Base3 = _interopRequireDefault(_Base2);

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

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var ORPHAN_THRESHOLD = 15;

var SubPage = function (_Base) {
  _inherits(SubPage, _Base);

  function SubPage(root, props, number) {
    _classCallCheck(this, SubPage);

    var _this = _possibleConstructorReturn(this, (SubPage.__proto__ || Object.getPrototypeOf(SubPage)).call(this, root, props));

    _this._number = number;
    return _this;
  }

  _createClass(SubPage, [{
    key: 'resetMargins',
    value: function resetMargins() {
      if (!!this.style.marginTop || !!this.style.marginBottom || !!this.style.marginLeft || !!this.style.marginRight) {
        (0, _warning2.default)(false, 'Margin values are not allowed on Page element. Use padding instead.');

        this.style.marginTop = 0;
        this.style.marginBottom = 0;
        this.style.marginLeft = 0;
        this.style.marginRight = 0;
      }
    }
  }, {
    key: 'applyProps',
    value: function applyProps() {
      _get(SubPage.prototype.__proto__ || Object.getPrototypeOf(SubPage.prototype), 'applyProps', this).call(this);
      this.resetMargins();

      if (this.props.size) {
        var size = this.size;

        if (this.props.orientation === 'landscape') {
          this.layout.setWidth(size[1]);
        } else {
          this.layout.setWidth(size[0]);
        }
      }
    }
  }, {
    key: 'recalculateLayout',
    value: function recalculateLayout() {
      _get(SubPage.prototype.__proto__ || Object.getPrototypeOf(SubPage.prototype), 'recalculateLayout', this).call(this);
      this.layout.calculateLayout();
    }
  }, {
    key: 'isEmpty',
    value: function isEmpty() {
      var nonFixedChilds = this.children.filter(function (child) {
        return !child.props.fixed;
      });
      if (nonFixedChilds.length === 0) {
        return true;
      }

      return nonFixedChilds.every(function (child) {
        return child.isEmpty();
      });
    }
  }, {
    key: 'wrap',
    value: function wrap(height) {
      this.layout.calculateLayout();

      var nextPageElements = [];
      var result = this.clone();

      result._number = this._number + 1;

      for (var i = 0; i < this.children.length; i++) {
        var child = this.children[i];
        var _child$props = child.props,
            fixed = _child$props.fixed,
            wrap = _child$props.wrap,
            orphan = _child$props.orphan;


        var childBottom = child.top + child.height;
        var isElementOutside = height < child.top;
        var shouldElementSplit = height < childBottom;
        var orphanThreshold = child.props.orphanThreshold || ORPHAN_THRESHOLD;
        var isElementOrphan = !orphan && height - childBottom < orphanThreshold;

        if (fixed) {
          var fixedElement = child.clone();
          fixedElement.children = child.children;
          result.appendChild(fixedElement);
        } else if (isElementOutside || isElementOrphan) {
          nextPageElements.push(child);
        } else if (child.props.break) {
          child.props.break = false;
          nextPageElements.push.apply(nextPageElements, _toConsumableArray(this.children.slice(i)));
          break;
        } else if (shouldElementSplit) {
          var remainingHeight = height - child.top + this.paddingTop;

          if (!wrap) {
            nextPageElements.push(child);
          } else {
            result.appendChild(child.splice(remainingHeight, height));
          }
        }
      }

      nextPageElements.forEach(function (child) {
        return child.moveTo(result);
      });
      result.applyProps();

      return result;
    }
  }, {
    key: 'callChildFunctions',
    value: function callChildFunctions() {
      var listToExplore = this.children.slice(0);

      while (listToExplore.length > 0) {
        var node = listToExplore.shift();
        var pageCount = this.page.document.pageCount;


        if (node.renderCallback) {
          var callResult = node.renderCallback({
            totalPages: pageCount,
            pageNumber: this.number
          });

          node.renderCallback = null;
          node.children = [callResult];
          continue;
        }

        if (node.children) {
          listToExplore.push.apply(listToExplore, _toConsumableArray(node.children));
        }
      }
    }
  }, {
    key: 'layoutFixedElements',
    value: function layoutFixedElements() {
      this.reset();
      this.layout.setHeight(this.size[1]);
      this.recalculateLayout();

      this.children.forEach(function (child) {
        if (child.props.fixed) {
          child.reset();
        }
      });
    }
  }, {
    key: 'render',
    value: function () {
      var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(page) {
        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                this.root.addPage({
                  size: this.size,
                  layout: this.props.orientation,
                  margin: 0
                });

                this.callChildFunctions();
                this.layoutFixedElements();

                if (this.style.backgroundColor) {
                  this.root.fillColor(this.style.backgroundColor).rect(0, 0, this.root.page.width, this.root.page.height).fill();
                }

                if (this.props.debug) {
                  this.debug();
                }

                _context.next = 7;
                return this.renderChildren(page);

              case 7:
              case 'end':
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function render(_x) {
        return _ref.apply(this, arguments);
      }

      return render;
    }()
  }, {
    key: 'page',
    get: function get() {
      return this.parent;
    }
  }, {
    key: 'size',
    get: function get() {
      return this.parent.size;
    }
  }, {
    key: 'style',
    get: function get() {
      return this.parent.style;
    },
    set: function set(style) {
      return style;
    }
  }, {
    key: 'number',
    get: function get() {
      return this._number + this.page.numberOffset;
    }
  }]);

  return SubPage;
}(_Base3.default);

exports.default = SubPage;