"use strict";
/*

Originally copied from: https://github.com/Viglino/ol-ext/blob/master/src/legend/Legend.js

BSD 3-Clause License

Copyright (c) 2016-2021, Jean-Marc Viglino, IGN-France
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its
   contributors may be used to endorse or promote products derived from
   this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.getLegendImage = void 0;
var tslib_1 = require("tslib");
var has_1 = require("ol/has");
var render_1 = require("ol/render");
var Feature_1 = tslib_1.__importDefault(require("ol/Feature"));
var Point_1 = tslib_1.__importDefault(require("ol/geom/Point"));
var LineString_1 = tslib_1.__importDefault(require("ol/geom/LineString"));
var Polygon_1 = tslib_1.__importDefault(require("ol/geom/Polygon"));
var extent_1 = require("ol/extent");
var DEFAULT_SIZE = [16, 16];
/**
 * Get a symbol image for a given legend item
 * @param {LegendItemOptions} item
 * @param {HTMLCanvasElement|undefined} canvas a canvas to draw in, if none create one
 * @param {number|undefined} row row number to draw in canvas, default 0
 * @since 0.14
 */
function getLegendImage(item, canvas, row) {
    var _a;
    if (canvas === void 0) { canvas = undefined; }
    if (row === void 0) { row = 0; }
    item = item || {};
    if (typeof (item.margin) === 'undefined')
        item.margin = 10;
    var size = item.size || DEFAULT_SIZE;
    item.onload = item.onload || function () {
        setTimeout(function () {
            getLegendImage(item, canvas, row);
        }, 100);
    };
    var width = size[0] + 2 * item.margin;
    var height = item.lineHeight || (size[1] + 2 * item.margin);
    var ratio = has_1.DEVICE_PIXEL_RATIO;
    if (!canvas) {
        row = 0;
        canvas = document.createElement('canvas');
        canvas.width = width * ratio;
        canvas.height = height * ratio;
    }
    var ctx = canvas.getContext('2d');
    if (ctx) {
        ctx.save();
        var vectorContext = (0, render_1.toContext)(ctx, { pixelRatio: ratio });
        var typeGeom = item.typeGeom;
        var style = void 0;
        var feature = item.feature;
        if (!feature && typeGeom) {
            if (/Point/.test(typeGeom))
                feature = new Feature_1.default(new Point_1.default([0, 0]));
            else if (/LineString/.test(typeGeom))
                feature = new Feature_1.default(new LineString_1.default([0, 0]));
            else
                feature = new Feature_1.default(new Polygon_1.default([[[0, 0]]]));
            if (item.properties)
                feature.setProperties(item.properties);
        }
        if (feature) {
            style = feature.getStyle();
            if (typeof (style) === 'function')
                style = style(feature);
            if (!style) {
                style = typeof (item.style) === 'function' ? item.style(feature) : item.style || [];
            }
            typeGeom = (_a = feature.getGeometry()) === null || _a === void 0 ? void 0 : _a.getType();
        }
        else {
            style = [];
        }
        if (!(style instanceof Array))
            style = [style];
        var styles = style;
        var cx = width / 2;
        var cy = height / 2;
        var sx = size[0] / 2;
        var sy = size[1] / 2;
        var i = void 0;
        var s = void 0;
        // Get point offset
        if (typeGeom === 'Point') {
            var extent = null;
            for (var i_1 = 0; s = styles[i_1]; i_1++) {
                var img = s.getImage();
                // Refresh legend on image load
                if (img) {
                    var imgElt = img.getImage(devicePixelRatio);
                    // Check image is loaded
                    if (imgElt && imgElt.complete && !imgElt.naturalWidth) {
                        if (typeof (item.onload) === 'function') {
                            imgElt.addEventListener('load', function () {
                                setTimeout(function () {
                                    var _a;
                                    (_a = item.onload) === null || _a === void 0 ? void 0 : _a.call(item);
                                }, 100);
                            });
                        }
                        img.load();
                    }
                    // Check anchor to center the image
                    if (img.getAnchor) {
                        var anchor = img.getAnchor();
                        if (anchor) {
                            var si = img.getSize();
                            var dx = anchor[0] - si[0];
                            var dy = anchor[1] - si[1];
                            if (!extent) {
                                extent = [dx, dy, dx + si[0], dy + si[1]];
                            }
                            else {
                                (0, extent_1.extend)(extent, [dx, dy, dx + si[0], dy + si[1]]);
                            }
                        }
                    }
                }
            }
            if (extent) {
                cx = cx + (extent[2] + extent[0]) / 2;
                cy = cy + (extent[3] + extent[1]) / 2;
            }
        }
        // Draw image
        cy += (row * height) || 0;
        for (i = 0; s = style[i]; i++) {
            vectorContext.setStyle(s);
            switch (typeGeom) {
                case Point_1.default:
                case 'Point':
                case 'MultiPoint':
                    vectorContext.drawGeometry(new Point_1.default([cx, cy]));
                    break;
                case LineString_1.default:
                case 'LineString':
                case 'MultiLineString':
                    ctx.save();
                    ctx.rect(item.margin * ratio, 0, size[0] * ratio, canvas.height);
                    ctx.clip();
                    vectorContext.drawGeometry(new LineString_1.default([[cx - sx, cy], [cx + sx, cy]]));
                    ctx.restore();
                    break;
                case Polygon_1.default:
                case 'Polygon':
                case 'MultiPolygon':
                    vectorContext.drawGeometry(new Polygon_1.default([[[cx - sx, cy - sy], [cx + sx, cy - sy], [cx + sx, cy + sy], [cx - sx, cy + sy], [cx - sx, cy - sy]]]));
                    break;
            }
        }
        ctx.restore();
    }
    return canvas;
}
exports.getLegendImage = getLegendImage;
;
//# sourceMappingURL=legend.js.map