/**
 * DevExtreme (cjs/exporter/jspdf/common/rows_splitting.js)
 * Version: 22.1.3 (build 22180-0310)
 * Build date: Wed Jun 29 2022
 *
 * Copyright (c) 2012 - 2022 Developer Express Inc. ALL RIGHTS RESERVED
 * Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/
 */
"use strict";
exports.splitByPages = splitByPages;
var _type = require("../../../core/utils/type");
var _pdf_utils = require("./pdf_utils");
var _draw_utils = require("./draw_utils");

function _toConsumableArray(arr) {
    return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread()
}

function _nonIterableSpread() {
    throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")
}

function _unsupportedIterableToArray(o, minLen) {
    if (!o) {
        return
    }
    if ("string" === typeof o) {
        return _arrayLikeToArray(o, minLen)
    }
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if ("Object" === n && o.constructor) {
        n = o.constructor.name
    }
    if ("Map" === n || "Set" === n) {
        return Array.from(o)
    }
    if ("Arguments" === n || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) {
        return _arrayLikeToArray(o, minLen)
    }
}

function _iterableToArray(iter) {
    if ("undefined" !== typeof Symbol && null != iter[Symbol.iterator] || null != iter["@@iterator"]) {
        return Array.from(iter)
    }
}

function _arrayWithoutHoles(arr) {
    if (Array.isArray(arr)) {
        return _arrayLikeToArray(arr)
    }
}

function _arrayLikeToArray(arr, len) {
    if (null == len || len > arr.length) {
        len = arr.length
    }
    for (var i = 0, arr2 = new Array(len); i < len; i++) {
        arr2[i] = arr[i]
    }
    return arr2
}

function _extends() {
    _extends = Object.assign ? Object.assign.bind() : function(target) {
        for (var i = 1; i < arguments.length; i++) {
            var source = arguments[i];
            for (var key in source) {
                if (Object.prototype.hasOwnProperty.call(source, key)) {
                    target[key] = source[key]
                }
            }
        }
        return target
    };
    return _extends.apply(this, arguments)
}

function convertToCellsArray(rows) {
    return [].concat.apply([], rows.map((function(rowInfo) {
        return rowInfo.cells.filter((function(cell) {
            return !(0, _type.isDefined)(cell.pdfCell.isMerged)
        })).map((function(cellInfo) {
            return _extends({}, cellInfo.pdfCell._rect, {
                sourceCellInfo: _extends({}, cellInfo.pdfCell, {
                    gridCell: cellInfo.gridCell
                })
            })
        }))
    })))
}

function splitByPages(doc, rowsInfo, options, onSeparateRectHorizontally, onSeparateRectVertically) {
    if (0 === rowsInfo.length) {
        return [
            []
        ]
    }
    var maxBottomRight = {
        x: (0, _pdf_utils.getPageWidth)(doc) - options.margin.right,
        y: (0, _pdf_utils.getPageHeight)(doc) - options.margin.bottom
    };
    var headerRows = rowsInfo.filter((function(r) {
        return "header" === r.rowType
    }));
    var headerHeight = headerRows.reduce((function(accumulator, row) {
        return accumulator + row.height
    }), 0);
    var verticallyPages = splitRectsByPages(convertToCellsArray(rowsInfo), options.margin.top, "y", "h", (function(pagesLength, currentCoordinate) {
        var additionalHeight = pagesLength > 0 && options.repeatHeaders ? headerHeight : 0;
        return (0, _draw_utils.roundToThreeDecimals)(currentCoordinate + additionalHeight) <= (0, _draw_utils.roundToThreeDecimals)(maxBottomRight.y)
    }), (function(rect, currentPageMaxRectCoordinate, currentPageRects, rectsToSplit) {
        var args = {
            sourceRect: rect,
            topRect: {
                x: rect.x,
                y: rect.y,
                w: rect.w,
                h: currentPageMaxRectCoordinate - rect.y
            },
            bottomRect: {
                x: rect.x,
                y: currentPageMaxRectCoordinate,
                w: rect.w,
                h: rect.h - (currentPageMaxRectCoordinate - rect.y)
            }
        };
        onSeparateRectVertically(args);
        currentPageRects.push(args.topRect);
        rectsToSplit.push(args.bottomRect)
    }));
    if (options.repeatHeaders) {
        for (var i = 1; i < verticallyPages.length; i++) {
            verticallyPages[i].forEach((function(rect) {
                return rect.y += headerHeight
            }));
            var headerCells = convertToCellsArray(headerRows);
            headerCells.forEach((function(cell) {
                cell.y -= options.topLeft.y
            }));
            verticallyPages[i] = [].concat(_toConsumableArray(headerCells), _toConsumableArray(verticallyPages[i]))
        }
    }
    var pageIndex = 0;
    while (pageIndex < verticallyPages.length) {
        var horizontallyPages = splitRectsByPages(verticallyPages[pageIndex], options.margin.left, "x", "w", (function(pagesLength, currentCoordinate) {
            return (0, _draw_utils.roundToThreeDecimals)(currentCoordinate) <= (0, _draw_utils.roundToThreeDecimals)(maxBottomRight.x)
        }), (function(rect, currentPageMaxRectCoordinate, currentPageRects, rectsToSplit) {
            var args = {
                sourceRect: rect,
                leftRect: {
                    x: rect.x,
                    y: rect.y,
                    w: currentPageMaxRectCoordinate - rect.x,
                    h: rect.h
                },
                rightRect: {
                    x: currentPageMaxRectCoordinate,
                    y: rect.y,
                    w: rect.w - (currentPageMaxRectCoordinate - rect.x),
                    h: rect.h
                }
            };
            onSeparateRectHorizontally(args);
            currentPageRects.push(args.leftRect);
            rectsToSplit.push(args.rightRect)
        }));
        if (horizontallyPages.length > 1) {
            verticallyPages.splice.apply(verticallyPages, [pageIndex, 1].concat(_toConsumableArray(horizontallyPages)));
            pageIndex += horizontallyPages.length
        } else {
            pageIndex += 1
        }
    }
    return verticallyPages.map((function(rects) {
        return rects.map((function(rect) {
            return _extends({}, rect.sourceCellInfo, {
                _rect: rect
            })
        }))
    }))
}

function splitRectsByPages(rects, marginValue, coordinate, dimension, checkPredicate, onSeparateCallback) {
    var pages = [];
    var rectsToSplit = _toConsumableArray(rects);
    var _loop = function() {
        var currentPageMaxRectCoordinate = 0;
        var currentPageRects = rectsToSplit.filter((function(rect) {
            var currentRectCoordinate = rect[coordinate] + rect[dimension];
            if (checkPredicate(pages.length, currentRectCoordinate)) {
                if (currentPageMaxRectCoordinate <= currentRectCoordinate) {
                    currentPageMaxRectCoordinate = currentRectCoordinate
                }
                return true
            } else {
                return false
            }
        }));
        var rectsToSeparate = rectsToSplit.filter((function(rect) {
            var currentRectLeft = rect[coordinate];
            var currentRectRight = rect[coordinate] + rect[dimension];
            if (currentRectLeft < currentPageMaxRectCoordinate && currentPageMaxRectCoordinate < currentRectRight) {
                return true
            }
        }));
        rectsToSeparate.forEach((function(rect) {
            onSeparateCallback(rect, currentPageMaxRectCoordinate, currentPageRects, rectsToSplit);
            var index = rectsToSplit.indexOf(rect);
            if (-1 !== index) {
                rectsToSplit.splice(index, 1)
            }
        }));
        currentPageRects.forEach((function(rect) {
            var index = rectsToSplit.indexOf(rect);
            if (-1 !== index) {
                rectsToSplit.splice(index, 1)
            }
        }));
        rectsToSplit.forEach((function(rect) {
            rect[coordinate] = (0, _type.isDefined)(currentPageMaxRectCoordinate) ? rect[coordinate] - currentPageMaxRectCoordinate + marginValue : rect[coordinate]
        }));
        if (currentPageRects.length > 0) {
            pages.push(currentPageRects)
        } else {
            pages.push(rectsToSplit);
            return "break"
        }
    };
    while (rectsToSplit.length > 0) {
        var _ret = _loop();
        if ("break" === _ret) {
            break
        }
    }
    return pages
}
