import { _FieldFlag, _getInheritableProperty, _PdfAnnotationType, _PdfBaseStream, _PdfReference, PdfBrush, _convertPointToNumberArray, _convertPointsToNumberArrays, PdfRectangleAnnotation, PdfSquareAnnotation, PdfCircleAnnotation, PdfEllipseAnnotation } from '@syncfusion/ej2-pdf';
var _PdfRedactionProcessor = /** @class */ (function () {
    function _PdfRedactionProcessor() {
    }
    _PdfRedactionProcessor.prototype._updateContentStream = function (page, stream, options, document) {
        if (typeof (stream) !== 'undefined' && page._pageDictionary.has('Contents')) {
            var contents = page._pageDictionary.getRaw('Contents'); // eslint-disable-line
            var content = void 0;
            var ref = void 0;
            if (contents !== null && typeof contents !== 'undefined' && contents instanceof _PdfReference) {
                ref = contents;
                contents = page._crossReference._fetch(ref);
            }
            if (contents && contents instanceof _PdfBaseStream) {
                content = [ref];
            }
            else if (contents && Array.isArray(contents)) {
                content = contents;
            }
            else {
                content = [];
            }
            for (var i = 0; i < content.length; i++) {
                var reference = content[Number.parseInt(i.toString(), 10)]; // eslint-disable-line
                page._crossReference._cacheMap.delete(reference);
            }
            var restoreReference = page._crossReference._getNextReference();
            page._crossReference._cacheMap.set(restoreReference, stream);
            var pageContent = [];
            pageContent.push(restoreReference);
            page._pageDictionary.set('Contents', pageContent);
            page._pageDictionary._updated = true;
        }
        this._processAnnotation(page, options);
        this._processFormFields(page, options, document);
        for (var i = 0; i < options.length; i++) {
            var bounds = options[Number.parseInt(i.toString(), 10)].bounds;
            if (options[Number.parseInt(i.toString(), 10)]._appearanceEnabled) {
                options[Number.parseInt(i.toString(), 10)].appearance.normal._isNew = true;
                page.graphics.drawTemplate(options[Number.parseInt(i.toString(), 10)].appearance.normal, bounds);
            }
            else if (options[Number.parseInt(i.toString(), 10)].fillColor) {
                page.graphics.drawRectangle(bounds, new PdfBrush(options[Number.parseInt(i.toString(), 10)].fillColor));
            }
        }
    };
    _PdfRedactionProcessor.prototype._processFormFields = function (page, options, document) {
        var form = document.form;
        var isValidField = true;
        if (form) {
            for (var i = 0; i < form.count; i++) {
                var field = form.fieldAt(i);
                if (field && field.page !== page) {
                    continue;
                }
                var key = _getInheritableProperty(field._dictionary, 'FT', false, true, 'Parent');
                var fieldFlags = 0;
                var bounds = void 0;
                var flag = _getInheritableProperty(field._dictionary, 'Ff', false, true, 'Parent');
                if (typeof flag !== 'undefined') {
                    fieldFlags = flag;
                }
                var kids = void 0; // eslint-disable-line
                switch (key.name.toLowerCase()) {
                    case 'tx':
                        kids = field._dictionary.getRaw('Kids');
                        if (kids && kids.length > 1) {
                            for (var i_1 = 0; i_1 < kids.length; i_1++) {
                                var kidsDictionary = document._crossReference._fetch(kids[Number.parseInt(i_1.toString(), 10)]);
                                if (kidsDictionary.has('Rect')) {
                                    var rectangle = kidsDictionary.getArray('Rect'); // eslint-disable-line
                                    if (rectangle) {
                                        bounds = this._toRectangle(rectangle[0], rectangle[1], rectangle[2], rectangle[3]);
                                        bounds.y = (page.graphics._size.height - (bounds.y + bounds.height));
                                    }
                                    var emptyRectangle = this._isEmptyRectangle(bounds.width, bounds.height);
                                    if (!emptyRectangle) {
                                        for (var j = 0; j < options.length; j++) {
                                            if (this._isFound(bounds, options[Number.parseInt(j.toString(), 10)].bounds) &&
                                                this._isKidInSamePage(kidsDictionary, page)) {
                                                if (page._pageDictionary.has('Annots')) {
                                                    var annots = page._pageDictionary.getRaw('Annots'); // eslint-disable-line
                                                    if (annots instanceof _PdfReference) {
                                                        var values = document._crossReference._fetch(annots); // eslint-disable-line
                                                        annots = values;
                                                    }
                                                    var index = annots.indexOf(kids[Number.parseInt(i_1.toString(), 10)]);
                                                    annots.splice(index, 1);
                                                    page._pageDictionary._updated = true;
                                                }
                                                isValidField = false;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else {
                            bounds = field.bounds;
                        }
                        break;
                    case 'btn':
                        if ((fieldFlags & _FieldFlag.pushButton) !== 0) {
                            bounds = field.bounds;
                        }
                        else if ((fieldFlags & _FieldFlag.radio) !== 0) {
                            kids = field._dictionary.getRaw('Kids');
                            if (kids && kids.length > 0) {
                                for (var i_2 = 0; i_2 < kids.length; i_2++) {
                                    var kidsDictionary = document._crossReference._fetch(kids[Number.parseInt(i_2.toString(), 10)]);
                                    if (kidsDictionary.has('Rect')) {
                                        var rectangle = kidsDictionary.getArray('Rect'); // eslint-disable-line
                                        if (rectangle) {
                                            bounds = this._toRectangle(rectangle[0], rectangle[1], rectangle[2], rectangle[3]);
                                            bounds.y = (page.graphics._size.height - (bounds.y + bounds.height));
                                        }
                                        var emptyRectangle = this._isEmptyRectangle(bounds.width, bounds.height);
                                        if (!emptyRectangle) {
                                            for (var j = 0; j < options.length; j++) {
                                                if (this._isFound(bounds, options[Number.parseInt(j.toString(), 10)].bounds)) {
                                                    if (page._pageDictionary.has('Annots')) {
                                                        var annots = page._pageDictionary.getRaw('Annots'); // eslint-disable-line
                                                        if (annots instanceof _PdfReference) {
                                                            var values = document._crossReference._fetch(annots); // eslint-disable-line
                                                            annots = values;
                                                        }
                                                        var index = annots.indexOf(kids[Number.parseInt(i_2.toString(), 10)]);
                                                        annots.splice(index, 1);
                                                        page._pageDictionary._updated = true;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            else {
                                bounds = field.bounds;
                            }
                        }
                        else {
                            bounds = field.bounds;
                        }
                        break;
                    case 'ch':
                        if ((fieldFlags & _FieldFlag.combo) !== 0) {
                            bounds = field.bounds;
                        }
                        else {
                            bounds = field.bounds;
                        }
                        break;
                    case 'sig':
                        bounds = field.bounds;
                        break;
                }
                var emptyBounds = this._isEmptyRectangle(bounds.width, bounds.height);
                if (isValidField && !emptyBounds) {
                    for (var j = 0; j < options.length; j++) {
                        if (this._isFound(bounds, options[Number.parseInt(j.toString(), 10)].bounds)) {
                            form.removeFieldAt(i);
                            i--;
                            break;
                        }
                    }
                }
                isValidField = true;
            }
        }
    };
    _PdfRedactionProcessor.prototype._isFound = function (values, redactionBounds) {
        if (this._intersectsWith(redactionBounds, values)) {
            return true;
        }
        return false;
    };
    _PdfRedactionProcessor.prototype._intersectsWith = function (rect1, rect2) {
        return (rect2.x < rect1.x + rect1.width) && (rect1.x < (rect2.x + rect2.width)) && (rect2.y < rect1.y + rect1.height) &&
            (rect1.y < rect2.y + rect2.height);
    };
    _PdfRedactionProcessor.prototype._isEmptyRectangle = function (width, height) {
        return (width <= 0 || height <= 0);
    };
    _PdfRedactionProcessor.prototype._toRectangle = function (x, y, width, height) {
        var x1 = Math.min(x, width);
        var y1 = Math.min(y, height);
        var x2 = Math.abs(x - width);
        var y2 = Math.abs(y - height);
        var bounds = { x: x1, y: y1, width: x2, height: y2 };
        return bounds;
    };
    _PdfRedactionProcessor.prototype._isKidInSamePage = function (kid, page) {
        var pageReference = page._ref;
        var reference = kid.getRaw('P');
        if (pageReference === reference) {
            return true;
        }
        else {
            return false;
        }
    };
    _PdfRedactionProcessor.prototype._checkAnnotationType = function (annotation) {
        var annotationType;
        if (annotation instanceof PdfRectangleAnnotation) {
            annotationType = _PdfAnnotationType.rectangleAnnotation;
        }
        else if (annotation instanceof PdfSquareAnnotation) {
            annotationType = _PdfAnnotationType.squareAnnotation;
        }
        else if (annotation instanceof PdfCircleAnnotation) {
            annotationType = _PdfAnnotationType.circleAnnotation;
        }
        else if (annotation instanceof PdfEllipseAnnotation) {
            annotationType = _PdfAnnotationType.ellipseAnnotation;
        }
        return annotationType;
    };
    _PdfRedactionProcessor.prototype._processAnnotation = function (page, options) {
        var markupAnnotation;
        var annotbounds = [];
        var _loop_1 = function (i) {
            var annotation = page.annotations.at(i);
            var type = void 0;
            var rect = void 0; // eslint-disable-line
            var bounds = void 0;
            if (typeof (annotation) !== 'undefined') {
                type = this_1._getAnnotationType(annotation._dictionary);
                rect = annotation.bounds;
                bounds = rect;
                if (typeof type === 'undefined' && !annotation._isLoaded) {
                    type = this_1._checkAnnotationType(annotation);
                }
            }
            else {
                type = _PdfAnnotationType.widgetAnnotation;
            }
            var isValidAnnotation = true;
            var newPoints = [];
            var inkBounds = void 0;
            switch (type) {
                case _PdfAnnotationType.textWebLinkAnnotation:
                case _PdfAnnotationType.documentLinkAnnotation:
                case _PdfAnnotationType.fileLinkAnnotation:
                case _PdfAnnotationType.watermarkAnnotation:
                case _PdfAnnotationType.fileAttachmentAnnotation:
                case _PdfAnnotationType.freeTextAnnotation:
                case _PdfAnnotationType.circleAnnotation:
                case _PdfAnnotationType.ellipseAnnotation:
                case _PdfAnnotationType.richMediaAnnotation:
                case _PdfAnnotationType.squareAnnotation:
                case _PdfAnnotationType.rectangleAnnotation:
                case _PdfAnnotationType.popupAnnotation:
                case _PdfAnnotationType.rubberStampAnnotation:
                case _PdfAnnotationType.soundAnnotation:
                case _PdfAnnotationType.linkAnnotation:
                    break;
                case _PdfAnnotationType.caretAnnotation:
                case _PdfAnnotationType.movieAnnotation:
                case _PdfAnnotationType.printerMarkAnnotation:
                case _PdfAnnotationType.textAnnotation:
                case _PdfAnnotationType.textMarkupAnnotation:
                case _PdfAnnotationType.trapNetworkAnnotation:
                    markupAnnotation = annotation;
                    if (markupAnnotation && markupAnnotation.boundsCollection && markupAnnotation.boundsCollection.length > 0) {
                        var isIntersect = false;
                        for (var _i = 0, _a = markupAnnotation.boundsCollection; _i < _a.length; _i++) {
                            var innerBounds = _a[_i];
                            for (var j = 0; j < options.length; j++) {
                                if (this_1._isFound(innerBounds, options[Number.parseInt(j.toString(), 10)].bounds)) {
                                    isIntersect = true;
                                    break;
                                }
                            }
                        }
                        if (isIntersect) {
                            page.annotations.removeAt(i);
                            i--;
                            return out_i_1 = i, "continue";
                        }
                    }
                    break;
                case _PdfAnnotationType.lineAnnotation:
                    {
                        var lineAnnotation = annotation;
                        var points = void 0;
                        if (lineAnnotation) {
                            points = lineAnnotation.linePoints;
                        }
                        var isFound = false;
                        var height = page.graphics._size.height;
                        for (var j = 0; j < options.length; j++) {
                            if (this_1._isLineIntersectRectangle(options[Number.parseInt(j.toString(), 10)].bounds, points[0].x, height - points[0].y, points[1].x, height - points[1].y)) {
                                isFound = true;
                            }
                        }
                        if (isFound) {
                            page.annotations.removeAt(i);
                            i--;
                            return out_i_1 = i, "continue";
                        }
                    }
                    break;
                case _PdfAnnotationType.polygonAnnotation:
                    {
                        var polygon = annotation;
                        var polygonPoints = polygon._getLinePoints();
                        var polygonPointsToArray = _convertPointToNumberArray(polygonPoints);
                        polygonPointsToArray.forEach(function (element) {
                            newPoints.push(element[0], -element[1]);
                        });
                        inkBounds = this_1._getBoundsFromPoints(newPoints, page);
                        bounds = inkBounds.bounds;
                        isValidAnnotation = inkBounds.isValidAnnotation;
                    }
                    break;
                case _PdfAnnotationType.polyLineAnnotation:
                    {
                        var polyLine = annotation;
                        var polyLinePoints = polyLine._getLinePoints();
                        var polyLinePointsToArray = _convertPointToNumberArray(polyLinePoints);
                        polyLinePointsToArray.forEach(function (element) {
                            newPoints.push(element[0], -element[1]);
                        });
                        inkBounds = this_1._getBoundsFromPoints(newPoints, page);
                        bounds = inkBounds.bounds;
                        isValidAnnotation = inkBounds.isValidAnnotation;
                    }
                    break;
                case _PdfAnnotationType.inkAnnotation:
                    {
                        var inkAnnotation = annotation;
                        var inkList = inkAnnotation.inkPointsCollection;
                        var inkPointsToNumberArray = _convertPointsToNumberArrays(inkList);
                        inkBounds = this_1._getBoundsFromPoints(inkPointsToNumberArray[0], page);
                        bounds = inkAnnotation.bounds;
                        if (!inkAnnotation._isLoaded) {
                            inkBounds.isValidAnnotation = true;
                        }
                        isValidAnnotation = inkBounds.isValidAnnotation;
                    }
                    break;
                case _PdfAnnotationType.highlight:
                case _PdfAnnotationType.squiggly:
                case _PdfAnnotationType.strikeOut:
                case _PdfAnnotationType.underline:
                case _PdfAnnotationType.screenAnnotation:
                    markupAnnotation = annotation;
                    if (markupAnnotation && markupAnnotation.boundsCollection && markupAnnotation.boundsCollection.length > 0) {
                        var isIntersect = false;
                        for (var _b = 0, _c = markupAnnotation.boundsCollection; _b < _c.length; _b++) {
                            var innerBounds = _c[_b];
                            for (var j = 0; j < options.length; j++) {
                                if (this_1._isFound(innerBounds, options[Number.parseInt(j.toString(), 10)].bounds)) {
                                    isIntersect = true;
                                    break;
                                }
                            }
                        }
                        if (isIntersect) {
                            page.annotations.removeAt(i);
                            i--;
                            return out_i_1 = i, "continue";
                        }
                    }
                    break;
                default:
                    isValidAnnotation = false;
            }
            annotbounds.push(bounds);
            if (bounds && isValidAnnotation) {
                for (var j = 0; j < options.length; j++) {
                    if (this_1._isFound(bounds, options[Number.parseInt(j.toString(), 10)].bounds)) {
                        page.annotations.removeAt(i);
                        i--;
                        page._pageDictionary._updated = true;
                        break;
                    }
                }
            }
            out_i_1 = i;
        };
        var this_1 = this, out_i_1;
        for (var i = 0; i <= page.annotations.count - 1; i++) {
            _loop_1(i);
            i = out_i_1;
        }
    };
    _PdfRedactionProcessor.prototype._getBoundsFromPoints = function (points, loadedPage) {
        var isValidAnnotation = false;
        if (points && Array.isArray(points) && points.length > 0) {
            var minX = points[0];
            var maxX = points[0];
            var minY = loadedPage.graphics._size.height - points[1];
            var maxY = loadedPage.graphics._size.height - points[1];
            for (var index = 0; index < points.length; index++) {
                var point = points[Number.parseInt(index.toString(), 10)];
                if (index % 2 === 0) {
                    minX = Math.min(minX, point);
                    maxX = Math.max(maxX, point);
                }
                else {
                    var adjustedY = loadedPage.graphics._size.height - point;
                    minY = Math.min(minY, adjustedY);
                    maxY = Math.max(maxY, adjustedY);
                }
            }
            isValidAnnotation = true;
            return { bounds: { x: minX, y: minY, width: maxX - minX, height: maxY - minY }, isValidAnnotation: isValidAnnotation };
        }
        return { bounds: { x: 0, y: 0, width: 0, height: 0 }, isValidAnnotation: isValidAnnotation };
    };
    _PdfRedactionProcessor.prototype._isLineIntersectRectangle = function (redactBounds, p1X, p1Y, p2X, p2Y) {
        var minX = p1X;
        var maxX = p2X;
        if (p1X > p2X) {
            minX = p2X;
            maxX = p1X;
        }
        if (maxX > redactBounds.x + redactBounds.width) {
            maxX = redactBounds.x + redactBounds.width;
        }
        if (minX < redactBounds.x) {
            minX = redactBounds.x;
        }
        if (minX > maxX) {
            return false;
        }
        var minY = p1Y;
        var maxY = p2Y;
        var dx = p2X - p1X;
        if (dx > 0.0000001) {
            var a = (p2Y - p1Y) / dx;
            var b = p1Y - a * p1X;
            minY = a * minX + b;
            maxY = a * maxX + b;
        }
        if (minY > maxY) {
            var temp = maxY;
            maxY = minY;
            minY = temp;
        }
        if (maxY > redactBounds.y + redactBounds.height) {
            maxY = redactBounds.y + redactBounds.height;
        }
        if (minY < redactBounds.y) {
            minY = redactBounds.y;
        }
        if (minY > maxY) {
            return false;
        }
        return true;
    };
    _PdfRedactionProcessor.prototype._isBoundsEqual = function (bounds1, bounds2) {
        return bounds1.x === bounds2.x &&
            bounds1.y === bounds2.y &&
            bounds1.width === bounds2.width &&
            bounds1.height === bounds2.height;
    };
    _PdfRedactionProcessor.prototype._getAnnotationType = function (dictionary) {
        var name = '';
        if (dictionary && dictionary.has('Subtype')) {
            var subtype = dictionary.get('Subtype');
            if (subtype) {
                name = subtype.name;
            }
        }
        var type;
        switch (name.toLowerCase()) {
            case 'sound':
                type = _PdfAnnotationType.soundAnnotation;
                break;
            case 'text':
            case 'popup':
                type = _PdfAnnotationType.popupAnnotation;
                break;
            case 'link':
                {
                    var linkDic = null;
                    if (dictionary.has('A')) {
                        linkDic = dictionary.get('A');
                    }
                    if (linkDic !== null && linkDic.has('S')) {
                        name = linkDic.get('S').name;
                        if (name != null) {
                            var border = [];
                            if (dictionary.has('Border')) {
                                border = dictionary.getArray('Border');
                            }
                            var mType = this._findAnnotation(border);
                            if (name === 'URI') {
                                if (!mType) {
                                    type = _PdfAnnotationType.linkAnnotation;
                                }
                                else {
                                    type = _PdfAnnotationType.textWebLinkAnnotation;
                                }
                            }
                            else if (name === 'Launch') {
                                type = _PdfAnnotationType.fileLinkAnnotation;
                            }
                            else if (name === 'GoToR') {
                                type = _PdfAnnotationType.linkAnnotation;
                            }
                            else if (name === 'GoTo') {
                                type = _PdfAnnotationType.documentLinkAnnotation;
                            }
                        }
                    }
                    else if (typeof (dictionary) !== 'undefined' && dictionary.has('Subtype')) {
                        var strText = dictionary.get('Subtype');
                        if (typeof (strText) !== 'undefined' && strText !== null) {
                            switch (strText.name) {
                                case 'Link':
                                    type = _PdfAnnotationType.documentLinkAnnotation;
                                    break;
                            }
                        }
                    }
                }
                break;
            case 'fileattachment':
                type = _PdfAnnotationType.fileAttachmentAnnotation;
                break;
            case 'line':
                type = _PdfAnnotationType.lineAnnotation;
                break;
            case 'circle':
                {
                    var circleRectArray = dictionary.getArray('Rect');
                    if (circleRectArray != null) {
                        var circleRect = circleRectArray;
                        type = (circleRect[2] === (circleRect[3])) ? _PdfAnnotationType.circleAnnotation :
                            _PdfAnnotationType.ellipseAnnotation;
                    }
                }
                break;
            case 'square':
                {
                    var squarerectArray = dictionary.getArray('Rect');
                    if (squarerectArray != null) {
                        var squareRect = squarerectArray;
                        type = (squareRect[2] === (squareRect[3])) ? _PdfAnnotationType.squareAnnotation :
                            _PdfAnnotationType.rectangleAnnotation;
                    }
                }
                break;
            case 'polygon':
                type = _PdfAnnotationType.polygonAnnotation;
                break;
            case 'redact':
                type = _PdfAnnotationType.redactionAnnotation;
                break;
            case 'polyline':
                type = _PdfAnnotationType.polyLineAnnotation;
                break;
            case 'widget':
                type = _PdfAnnotationType.widgetAnnotation;
                break;
            case 'highlight':
                type = _PdfAnnotationType.highlight;
                break;
            case 'underline':
                type = _PdfAnnotationType.underline;
                break;
            case 'strikeout':
                type = _PdfAnnotationType.strikeOut;
                break;
            case 'squiggly':
                type = _PdfAnnotationType.squiggly;
                break;
            case 'stamp':
                type = _PdfAnnotationType.rubberStampAnnotation;
                break;
            case 'ink':
                type = _PdfAnnotationType.inkAnnotation;
                break;
            case 'freetext':
                type = _PdfAnnotationType.freeTextAnnotation;
                break;
            case 'caret':
                type = _PdfAnnotationType.caretAnnotation;
                break;
            case 'watermark':
                type = _PdfAnnotationType.watermarkAnnotation;
                break;
            case 'screen':
                type = _PdfAnnotationType.screenAnnotation;
                break;
            case '3d':
                type = _PdfAnnotationType.movieAnnotation;
                break;
            case 'richmedia':
                type = _PdfAnnotationType.richMediaAnnotation;
                break;
        }
        return type;
    };
    _PdfRedactionProcessor.prototype._findAnnotation = function (array) {
        if (typeof (array) === 'undefined') {
            return false;
        }
        for (var i = 0; i < array.length; i++) {
            if (array[Number.parseInt(i.toString(), 10)] instanceof Array) {
                var temp = array[Number.parseInt(i.toString(), 10)]; // eslint-disable-line
                for (var j = 0; j < temp.length; j++) {
                    var value = temp[Number.parseInt(i.toString(), 10)];
                    if (value > 0) {
                        return false;
                    }
                }
            }
            else {
                var digit = array[Number.parseInt(i.toString(), 10)];
                if (typeof (digit) !== 'undefined' && digit > 0) {
                    return false;
                }
            }
        }
        return true;
    };
    return _PdfRedactionProcessor;
}());
export { _PdfRedactionProcessor };
