"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var Emitter_1 = __importDefault(require("./Emitter"));
var Hammer = __importStar(require("hammerjs"));
var ua_parser_js_1 = require("ua-parser-js");
var promise_1 = __importDefault(require("promise"));
// import { PDFJS } from 'pdfjs-dist'
var Helpers_1 = __importDefault(require("./Helpers"));
var helpers = new Helpers_1.default();
// Main/public page service
var storage, config;
var PdfWrap = /** @class */ (function () {
    function PdfWrap(
    // interval: any,
    ippStorage, ippConf) {
        storage = ippStorage;
        config = ippConf;
        return Pdf;
    }
    return PdfWrap;
}());
exports.default = PdfWrap;
var Pdf = /** @class */ (function (_super) {
    __extends(Pdf, _super);
    function Pdf(container) {
        var _this = _super.call(this) || this;
        _this.container = container;
        _this.data = [];
        _this.rendering = false;
        // public canvasId: string = "pdfCanvas";
        _this.annotationId = 'pdfAnnotations';
        _this.pdfPages = 1;
        _this.pdfPage = 1;
        _this._fit = 'contain';
        _this.touch = false;
        _this.scale = 1;
        _this.ratio = 1;
        _this.ratioScale = 1;
        _this.scrollbars = {
            width: 8,
            inset: false,
            scrolling: false,
            x: {
                size: 0,
                offset: 0,
                offsetPercent: 0,
                label: 'width',
                style: 'margin-left',
                show: false,
                anchor: 'left',
                track: undefined,
                handle: undefined
            },
            y: {
                size: 0,
                offset: 0,
                offsetPercent: 0,
                label: 'height',
                style: 'margin-top',
                show: false,
                anchor: 'top',
                track: undefined,
                handle: undefined
            }
        };
        _this.onResizeEvent = function () {
            // this.setFit(this.fit);
            _this.setAnnotationsBounds();
            _this.updateScrollbars();
            _this.setFit(_this.fit);
        };
        _this.onWheelEvent = function (evt) {
            if (_this.fit === 'contain')
                return;
            if (_this.fit === 'width' && _this.containerBounds.height > _this.canvasBounds.height)
                return;
            if (_this.fit === 'height' && _this.containerBounds.width > _this.canvasBounds.width)
                return;
            var offset = Math.abs(evt.deltaY) >= 100 ? Math.round(Math.abs(evt.deltaY) / 5) : 20;
            var direction = evt.deltaY > 0 ? 1 : -1;
            offset *= direction;
            var axis = 'y';
            if (_this.canvasBounds.height <= _this.containerBounds.height &&
                _this.canvasBounds.width > _this.containerBounds.width) {
                axis = 'x';
            }
            console.log(axis, offset);
            _this.moveScrollbarTrack(axis, offset);
        };
        _this.onMouseUp = function () {
            console.log('onMouseUp');
            _this.scrollbars.scrolling = false;
            ['x', 'y'].forEach(function (axis) {
                _this.scrollbars[axis].drag = false;
            });
        };
        _this.onMouseDown = function (evt) {
            var scrollHandle = false;
            ['x', 'y'].forEach(function (axis) {
                if (_this.scrollbars[axis].handle === evt.target)
                    scrollHandle = true;
            });
            if (scrollHandle)
                return;
            if (helpers.isTarget(_this.containerEl, evt.target)) {
                _this.emit(_this.ON_FOCUS);
            }
        };
        _this.onKeydown = function (evt) {
            switch (evt.keyCode) {
                // left
                case 37:
                    _this.page('prev');
                    break;
                // right
                case 39:
                    _this.page('next');
                    break;
            }
        };
        _this.onMouseMove = function (evt) {
            ['x', 'y'].forEach(function (axis) {
                if (!_this.scrollbars[axis].drag || !_this.scrollbars.scrolling) {
                    return;
                }
                // check if handle has reached limits
                var offset = evt[axis] - _this.scrollbars[axis].start;
                _this.moveScrollbarTrack(axis, offset);
                _this.scrollbars[axis].start = evt[axis];
            });
        };
        _this.destroy();
        var parser = new ua_parser_js_1.UAParser();
        var parseResult = parser.getResult();
        _this.touch = parseResult.device && (parseResult.device.type === 'tablet' || parseResult.device.type === 'mobile');
        _this.pdfLink = new PdfLink();
        _this.pdfLink.register(function (name, value) {
            console.log('pdf', name, value);
            if (name === _this.pdfLink.ON_GOTO_PAGE) {
                _this.pdfPage = value;
                _this.renderPdf();
            }
        });
        if (typeof container === 'string') {
            _this.containerEl = document.getElementById(container);
        }
        else {
            _this.containerEl = container;
        }
        _this.containerEl.style['overflow'] = _this.touch ? 'auto' : 'hidden';
        _this.containerEl.style['text-align'] = 'center';
        // create pdf canvas
        _this.canvasEl = document.createElement('canvas');
        // create anotations layer
        _this.annotationsEl = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
        _this.annotationsEl.style['position'] = 'absolute';
        _this.annotationsEl.style['z-index'] = '1';
        _this.annotationsEl.style['left'] = '0';
        _this.annotationsEl.style['top'] = '0';
        // this.annotationsEl.style["width"] = "100%";
        _this.containerEl.appendChild(_this.canvasEl);
        _this.containerEl.appendChild(_this.annotationsEl);
        _this.ratio = window.devicePixelRatio;
        _this.scale = _this.ratio;
        _this.ratioScale = _this.scale;
        if (_this.touch) {
            _this.setupTouch();
        }
        else {
            _this.containerEl.addEventListener('wheel', _this.onWheelEvent, false);
            window.addEventListener('mouseup', _this.onMouseUp, false);
            window.addEventListener('mousedown', _this.onMouseDown, false);
            window.addEventListener('mousemove', _this.onMouseMove, false);
            window.addEventListener('keydown', _this.onKeydown, false);
            _this.createScrollbars();
        }
        window.addEventListener('resize', _this.onResizeEvent);
        return _this;
    }
    Object.defineProperty(Pdf.prototype, "ON_LOADING", {
        // public static $inject: string[] = [
        //     "$timeout",
        //     "$interval",
        //     "$q",
        //     "ippStorageService",
        //     "CONFIG",
        // ];
        get: function () {
            return 'loading';
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Pdf.prototype, "ON_LOADED", {
        get: function () {
            return 'loaded';
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Pdf.prototype, "ON_FOCUS", {
        get: function () {
            return 'focus';
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Pdf.prototype, "fit", {
        get: function () {
            return this._fit;
        },
        set: function (value) {
            if (['scroll', 'width', 'height', 'contain'].indexOf(value) === -1) {
                return;
            }
            this._fit = value;
        },
        enumerable: true,
        configurable: true
    });
    Pdf.prototype.destroy = function () {
        if (!this.containerEl) {
            return;
        }
        document.removeEventListener('resize', this.onResizeEvent);
        this.containerEl.innerHTML = '';
        if (this.hammer) {
            this.hammer.destroy();
        }
        else {
            this.containerEl.removeEventListener('wheel', this.onWheelEvent, false);
            window.removeEventListener('mouseup', this.onMouseUp, false);
            window.removeEventListener('mousedown', this.onMouseDown, false);
            window.removeEventListener('mousemove', this.onMouseMove, false);
            window.removeEventListener('keydown', this.onKeydown, false);
        }
    };
    Pdf.prototype.render = function (data) {
        var _this = this;
        var p = new promise_1.default(function (resolve, reject) {
            // check if we a url
            _this.data = data;
            if (!_this.data || !_this.data[0] || !_this.data[0][0]) {
                reject(false);
                return;
            }
            // get url
            _this.fileUrl = _this.handleURL(_this.data[0][0].formatted_value || _this.data[0][0].value);
            // start render
            _this.rendering = true;
            // setup httpHeaders
            var headers = {};
            if (_this.fileUrl.indexOf('ipushpull.') >= 0) {
                headers = {
                    Authorization: 'Bearer ' + storage.persistent.get('access_token'),
                    'x-ipp-client': config.api_key
                };
            }
            if (!_this.fileUrl) {
                reject({ message: 'File not found' });
                return;
            }
            // load pdf into memory
            var loading = PDFJS.getDocument({
                url: _this.fileUrl,
                httpHeaders: headers
            }, undefined, undefined, function (result) {
                _this.emit(_this.ON_LOADING, result);
            });
            loading.then(function (pdf) {
                _this.pdfObj = pdf;
                _this.pdfLink.setDocument(pdf);
                _this.pdfPages = pdf.numPages;
                _this.renderPdf();
                resolve(true);
            }, function (err) {
                reject(err);
            });
        });
        return p;
    };
    Pdf.prototype.setFit = function (dimension) {
        if (['scroll', 'width', 'height', 'contain'].indexOf(dimension) === -1) {
            return;
        }
        this.fit = dimension;
        if (dimension === 'scroll') {
            this.canvasEl.style['width'] = 'auto';
            this.canvasEl.style['height'] = 'auto';
        }
        else if (dimension === 'width') {
            this.canvasEl.style['width'] = '100%';
            this.canvasEl.style['height'] = 'auto';
        }
        else if (dimension === 'height') {
            this.canvasEl.style['width'] = 'auto';
            this.canvasEl.style['height'] = '100%';
        }
        else if (dimension === 'contain') {
            var containerBounds = this.containerEl.getBoundingClientRect();
            var canvasBounds = this.canvasEl.getBoundingClientRect();
            var canvasProp = this.canvasEl.width / this.canvasEl.height;
            var containerProp = containerBounds.width / containerBounds.height;
            if (canvasProp > containerProp) {
                this.canvasEl.style['width'] = '100%';
                this.canvasEl.style['height'] = 'auto';
            }
            else {
                this.canvasEl.style['width'] = 'auto';
                this.canvasEl.style['height'] = '100%';
            }
        }
        this.containerEl.scrollLeft = 0;
        this.containerEl.scrollTop = 0;
        this.resetScrollbars();
        this.setAnnotationsBounds();
        this.updateScrollbars();
    };
    Pdf.prototype.page = function (direction) {
        if (direction === 'next') {
            this.pdfPage++;
        }
        else if (direction === 'prev') {
            this.pdfPage--;
        }
        else {
            this.pdfPage = parseInt(direction, 10);
        }
        this.setPage();
    };
    Pdf.prototype.resetScrollbars = function () {
        var _this = this;
        ['x', 'y'].forEach(function (axis) {
            var anchor = _this.scrollbars[axis].anchor;
            _this.scrollbars[axis].offset = 0;
            _this.scrollbars[axis].size = 0;
            _this.scrollbars[axis].show = false;
            _this.canvasEl.style[_this.scrollbars[axis].style] = "0px";
            _this.annotationsEl.style[_this.scrollbars[axis].style] = "0px";
            if (_this.scrollbars[axis].handle) {
                _this.scrollbars[axis].handle.style[anchor] = "0px";
            }
        });
    };
    Pdf.prototype.moveScrollbarTrack = function (axis, offset) {
        this.scrollbars[axis].offset += offset;
        // check if handle has reached limits
        var dimension = this.scrollbars[axis].label;
        var canvasSize = this.canvasBounds[dimension];
        // let size = this.containerBounds[dimension] * (this.containerBounds[dimension] / canvasSize);
        var distance = this.containerBounds[dimension] - this.scrollbars[axis].size;
        // let offset = evt[axis] - this.scrollbars[axis].start + this.scrollbars[axis].offset;
        if (this.scrollbars[axis].offset > distance) {
            this.scrollbars[axis].offset = distance;
        }
        else if (this.scrollbars[axis].offset < 0) {
            this.scrollbars[axis].offset = 0;
        }
        // new index based on how far scroll has moved
        var anchor = this.scrollbars[axis].anchor;
        this.scrollbars[axis].handle.style[anchor] = this.scrollbars[axis].offset + "px";
        var offsetPercent = this.scrollbars[axis].offset / (this.containerBounds[dimension] - this.scrollbars[axis].size);
        var offsetDistance = (this.containerBounds[dimension] - this.canvasBounds[dimension]) * offsetPercent;
        this.scrollbars[axis].offsetPercent = offsetPercent;
        this.canvasEl.style[this.scrollbars[axis].style] = offsetDistance + "px";
        this.annotationsEl.style[this.scrollbars[axis].style] = offsetDistance + "px";
    };
    Pdf.prototype.createScrollbars = function () {
        var _this = this;
        ['x', 'y'].forEach(function (axis) {
            var anchor = _this.scrollbars[axis].anchor;
            _this.scrollbars[axis].track = document.createElement('div');
            _this.scrollbars[axis].handle = document.createElement('div');
            // setup track
            _this.scrollbars[axis].track.style['position'] = 'absolute';
            _this.scrollbars[axis].track.style['z-index'] = 10;
            _this.scrollbars[axis].track.style['display'] = 'none';
            _this.scrollbars[axis].track.className = 'track';
            // setup handle
            _this.scrollbars[axis].handle.style['position'] = 'absolute';
            _this.scrollbars[axis].handle.style['z-index'] = 1;
            _this.scrollbars[axis].handle.style['left'] = 0;
            _this.scrollbars[axis].handle.style['top'] = 0;
            _this.scrollbars[axis].handle.className = 'handle';
            _this.scrollbars[axis].handle.addEventListener('mousedown', function (evt) {
                console.log('mousedown');
                _this.scrollbars.scrolling = true;
                _this.scrollbars[axis].start = evt[axis];
                _this.scrollbars[axis].drag = true;
                _this.scrollbars[axis].offset = parseInt(_this.scrollbars[axis].handle.style[anchor], 10);
                // evt.stopPropagation();
                evt.preventDefault();
            }, false);
            // this.scrollbars[axis].handle.addEventListener("mouseenter", (evt: any) => {
            //     this.scrollbars[axis].pressed = true;
            //     evt.stopPropagation();
            // }, false);
            if (axis === 'x') {
                _this.scrollbars[axis].track.style['left'] = 0;
                _this.scrollbars[axis].track.style['bottom'] = 0;
                _this.scrollbars[axis].track.style['right'] = 0;
                _this.scrollbars[axis].track.style['height'] = _this.scrollbars.width + "px";
                _this.scrollbars[axis].handle.style['height'] = _this.scrollbars.width + "px";
            }
            else {
                _this.scrollbars[axis].track.style['top'] = 0;
                _this.scrollbars[axis].track.style['right'] = 0;
                _this.scrollbars[axis].track.style['bottom'] = 0;
                _this.scrollbars[axis].track.style['width'] = _this.scrollbars.width + "px";
                _this.scrollbars[axis].handle.style['width'] = _this.scrollbars.width + "px";
            }
            _this.scrollbars[axis].track.appendChild(_this.scrollbars[axis].handle);
            _this.containerEl.appendChild(_this.scrollbars[axis].track);
        });
    };
    Pdf.prototype.updateScrollbars = function () {
        var _this = this;
        if (this.touch) {
            return;
        }
        ['x', 'y'].forEach(function (axis) {
            // let offset = this.offsets[axis].index / this.offsets[axis].max * (canvasSize - size);
            // let anchor = this.scrollbars[axis].anchor;
            // this.scrollbars[axis].handle.style[anchor] = `${offset}px`;
            var dimension = _this.scrollbars[axis].label;
            if (_this.containerBounds[dimension] >= _this.canvasBounds[dimension]) {
                _this.scrollbars[axis].track.style.display = 'none';
                return;
            }
            var canvasSize = _this.canvasBounds[dimension];
            var size = _this.containerBounds[dimension] * (_this.containerBounds[dimension] / canvasSize);
            _this.scrollbars[axis].handle.style[dimension] = size + "px";
            _this.scrollbars[axis].size = size;
            var anchor = _this.scrollbars[axis].anchor;
            var offsetPercent = _this.scrollbars[axis].offsetPercent;
            var offsetDistance = (_this.containerBounds[dimension] - size) * offsetPercent;
            _this.scrollbars[axis].handle.style[anchor] = offsetDistance + "px";
            _this.scrollbars[axis].track.style.display = 'block';
            offsetDistance = (_this.containerBounds[dimension] - _this.canvasBounds[dimension]) * offsetPercent;
            _this.canvasEl.style[_this.scrollbars[axis].style] = offsetDistance + "px";
            _this.annotationsEl.style[_this.scrollbars[axis].style] = offsetDistance + "px";
        });
    };
    Pdf.prototype.setAnnotationsBounds = function () {
        this.containerBounds = this.containerEl.getBoundingClientRect();
        this.canvasBounds = this.canvasEl.getBoundingClientRect();
        // let width = this.canvasEl.style.width || `${canvasBounds.width}px`;
        // if (width === "auto" && this.canvasEl.style.height === "100%" || this.fit === "scroll") {
        //     this.annotationsEl.style.left = `${(canvasBounds.left - containerBounds.left)}px`;
        // } else {
        //     this.annotationsEl.style.left = `0px`;
        // }
        this.annotationsEl.style.left = this.canvasBounds.left - this.containerBounds.left + "px";
        this.annotationsEl.style.width = this.canvasBounds.width + "px";
        this.annotationsEl.style.height = this.canvasBounds.height + "px";
    };
    Pdf.prototype.setupTouch = function () {
        var _this = this;
        this.hammer = new Hammer.default(this.containerEl);
        var pan = new Hammer.Pan();
        var pinch = new Hammer.Pinch();
        this.hammer.add([pan, pinch]);
        var width;
        this.hammer.on('pinchstart', function (evt) {
            var rect = _this.canvasEl.getBoundingClientRect();
            width = rect.width;
            _this.fit = 'scroll';
            _this.canvasEl.style.width = width + "px";
            _this.canvasEl.style.height = "auto";
        });
        this.hammer.on('pinchmove', function (evt) {
            console.log(evt);
            _this.canvasEl.style.width = width * evt.scale + "px";
            _this.setAnnotationsBounds();
        });
        this.hammer.on('pinchend', function (evt) { });
        var offsets = { x: 0, y: 0, left: this.containerEl.scrollLeft, top: this.containerEl.scrollTop };
        this.hammer.on('panstart', function (evt) {
            offsets.x = evt.center.x;
            offsets.y = evt.center.y;
            offsets.left = _this.containerEl.scrollLeft;
            offsets.top = _this.containerEl.scrollTop;
        });
        this.hammer.on('panmove', function (evt) {
            _this.containerEl.scrollTop = offsets.top + offsets.y - evt.center.y;
            _this.containerEl.scrollLeft = offsets.left + offsets.x - evt.center.x;
        });
        this.hammer.on('panend', function (evt) { });
    };
    Pdf.prototype.setPage = function () {
        if (this.pdfPage > this.pdfPages) {
            this.pdfPage = 1;
        }
        else if (this.pdfPage <= 0) {
            this.pdfPage = this.pdfPages;
        }
        this.renderPdf();
    };
    Pdf.prototype.renderPdf = function () {
        var _this = this;
        var p = new promise_1.default(function (resolve, reject) {
            // get page
            _this.pdfObj.getPage(_this.pdfPage).then(function (page) {
                // get size of pdf
                var viewport = page.getViewport(2);
                // setup canvas
                var context = _this.canvasEl.getContext('2d');
                _this.canvasEl.height = viewport.height;
                _this.canvasEl.width = viewport.width;
                // render context
                var renderContext = {
                    canvasContext: context,
                    viewport: viewport
                };
                // finally render pdf
                var render = page.render(renderContext);
                render.promise.then(function (a) {
                    console.log('renderPdf', a);
                    _this.setFit(_this.fit);
                    _this.emit(_this.ON_LOADED, true);
                    _this.renderAnnotations(page, viewport, context);
                    resolve(a);
                }, reject);
            }, function (err) {
                console.log('renderPdf', err);
            });
        });
        return p;
    };
    Pdf.prototype.renderAnnotations = function (page, viewport, canvas) {
        var _this = this;
        var layer = this.annotationsEl;
        if (!layer) {
            return;
        }
        layer.innerHTML = '';
        this.setAnnotationsBounds();
        console.log('pdf', layer);
        var appendAnchor = function (element, url) {
            var svgNS = _this.annotationsEl.namespaceURI;
            var a = document.createElementNS(svgNS, 'a');
            a.setAttribute('class', 'pdf-link');
            a.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', '#');
            a.addEventListener('click', function (e) {
                console.log('pdf', 'click', url);
                if (url.link) {
                    window.open(url.link, '_blank');
                    e.preventDefault();
                }
                else if (url.internal) {
                    _this.page(url.page + 1);
                }
            });
            var rect = document.createElementNS(svgNS, 'rect');
            rect.setAttribute('x', element.rect[0]);
            rect.setAttribute('y', "" + (viewport.viewBox[3] - element.rect[3]));
            rect.setAttribute('width', "" + (element.rect[2] - element.rect[0]));
            rect.setAttribute('height', "" + (element.rect[3] - element.rect[1]));
            rect.setAttribute('fill', 'rgba(30,144,255,1)');
            // rect.setAttribute("stroke", "dodgerblue");
            // rect.setAttribute("stroke-width", "1");
            a.appendChild(rect);
            _this.annotationsEl.appendChild(a);
        };
        page.getAnnotations().then(function (annotationsData) {
            console.log(annotationsData);
            // annotationsData.rect[x, y, x2, y2] 196.764, 161.004, 414.036, 174.036   792
            viewport = viewport.clone({
                dontFlip: true
            });
            layer.setAttribute('viewBox', viewport.viewBox.join(' '));
            annotationsData.forEach(function (element) {
                if (element.dest && typeof element.dest === 'string') {
                    _this.pdfObj.getDestination(element.dest).then(function (res) {
                        console.log('pdf', res);
                        _this.pdfObj.getPageIndex(res[0]).then(function (page) {
                            console.log('pdf', page);
                            appendAnchor(element, { internal: true, page: page });
                        }, function (err) {
                            console.error('pdf', err);
                        });
                    }, function (err) {
                        console.error('pdf', err);
                    });
                }
                else if (element.url) {
                    appendAnchor(element, { link: element.url });
                }
            });
            // let annotationLayer: any = PDFJS.AnnotationLayer;
            // annotationLayer.render({
            //     annotations: annotationsData,
            //     div: layer,
            //     page: page,
            //     viewport: viewport,
            //     linkService: this.pdfLink,
            // });
        });
    };
    Pdf.prototype.handleURL = function (url) {
        if (url.indexOf('dropbox.com') > -1) {
            url = url.split('www.dropbox.com').join('dl.dropboxusercontent.com');
            return config.docs_url + "/default/relay?url=" + url;
        }
        return url;
    };
    return Pdf;
}(Emitter_1.default));
exports.Pdf = Pdf;
var PdfLink = /** @class */ (function (_super) {
    __extends(PdfLink, _super);
    function PdfLink() {
        var _this = _super.call(this) || this;
        _this._pagesRefCache = undefined;
        return _this;
    }
    Object.defineProperty(PdfLink.prototype, "ON_GOTO_PAGE", {
        get: function () {
            return 'goto_page';
        },
        enumerable: true,
        configurable: true
    });
    PdfLink.prototype.setDocument = function (pdfDocument, baseUrl) {
        this.baseUrl = baseUrl;
        this.pdfDocument = pdfDocument;
        this._pagesRefCache = {}; // Object.create(undefined);
    };
    Object.defineProperty(PdfLink.prototype, "pagesCount", {
        /**
         * @returns {number}
         */
        get: function () {
            return this.pdfDocument.numPages;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(PdfLink.prototype, "page", {
        /**
         * @returns {number}
         */
        get: function () {
            return this.pdfViewer.currentPageNumber;
        },
        /**
         * @param {number} value
         */
        set: function (value) {
            this.pdfViewer.currentPageNumber = value;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * @param dest - The PDF destination object.
     */
    PdfLink.prototype.navigateTo = function (dest) {
        var _this = this;
        var destString = '';
        var goToDestination = function (destRef) {
            // dest array looks like that: <page-ref> </XYZ|FitXXX> <args..>
            var pageNumber = destRef instanceof Object ? _this._pagesRefCache[destRef.num + ' ' + destRef.gen + ' R'] : destRef + 1;
            if (pageNumber) {
                if (pageNumber > _this.pagesCount) {
                    pageNumber = _this.pagesCount;
                }
                _this.emit(_this.ON_GOTO_PAGE, pageNumber);
                // $scope.goToPage(pageNumber); TODO !!
            }
            else {
                _this.pdfDocument.getPageIndex(destRef).then(function (pageIndex) {
                    var pageNum = pageIndex + 1;
                    var cacheKey = destRef.num + ' ' + destRef.gen + ' R';
                    _this._pagesRefCache[cacheKey] = pageNum;
                    goToDestination(destRef);
                });
            }
        };
        var destinationPromise;
        if (typeof dest === 'string') {
            destString = dest;
            destinationPromise = this.pdfDocument.getDestination(dest);
        }
        else {
            destinationPromise = promise_1.default.resolve(dest);
        }
        destinationPromise.then(function (destination) {
            dest = destination;
            if (!(destination instanceof Array)) {
                return; // invalid destination
            }
            goToDestination(destination[0]);
        });
    };
    /**
     * @param dest - The PDF destination object.
     * @returns {string} The hyperlink to the PDF object.
     */
    PdfLink.prototype.getDestinationHash = function (dest) {
        if (typeof dest === 'string') {
            return this.getAnchorUrl('#' + escape(dest));
        }
        if (dest instanceof Array) {
            var destRef = dest[0]; // see navigateTo method for dest format
            var pageNumber = destRef instanceof Object ? this._pagesRefCache[destRef.num + ' ' + destRef.gen + ' R'] : destRef + 1;
            if (pageNumber) {
                var pdfOpenParams = this.getAnchorUrl('#page=' + pageNumber);
                var destKind = dest[1];
                if (typeof destKind === 'object' && 'name' in destKind && destKind.name === 'XYZ') {
                    var scale = dest[4];
                    var scaleNumber = parseFloat(scale);
                    if (scaleNumber) {
                        scale = scaleNumber * 100;
                    }
                    pdfOpenParams += '&zoom=' + scale;
                    if (dest[2] || dest[3]) {
                        pdfOpenParams += ',' + (dest[2] || 0) + ',' + (dest[3] || 0);
                    }
                }
                return pdfOpenParams;
            }
        }
        return '';
    };
    /**
     * Prefix the full url on anchor links to make sure that links are resolved
     * relative to the current URL instead of the one defined in <base href>.
     * @param {String} anchor The anchor hash, including the #.
     * @returns {string} The hyperlink to the PDF object.
     */
    PdfLink.prototype.getAnchorUrl = function (anchor) {
        return (this.baseUrl || '') + anchor;
    };
    /**
     * @param {string} hash
     */
    // public setHash(hash) { },
    /**
     * @param {string} action
     */
    // public executeNamedAction(action) { }
    /**
     * @param {number} pageNum - page number.
     * @param {Object} pageRef - reference to the page.
     */
    PdfLink.prototype.cachePageRef = function (pageNum, pageRef) {
        var refStr = pageRef.num + ' ' + pageRef.gen + ' R';
        this._pagesRefCache[refStr] = pageNum;
    };
    return PdfLink;
}(Emitter_1.default));
//# sourceMappingURL=Pdf.js.map