var PopulationUtil = {
    range: {
        start: 0,
        end: 100,
        colors: ['lightskyblue', 'yellow', 'orangered']
    },
    colors: [],
    initRange: function (start, end, colors) {
        var range = {};
        if (start != null) {
            range.start = start;
        }
        if (end != null) {
            range.end = end;
        }
        if (z.type.isArray(colors)) {
            range.colors = colors;
        }
        z.util.mergeObject(PopulationUtil.range, range)
    },
    getRangeColor: function (population) {
        var colors = PopulationUtil.range.colors;
        if (population == null || population <= PopulationUtil.range.start) {
            return colors[0]
        }
        var count = colors.length;
        if (population >= PopulationUtil.range.end) {
            return colors[count - 1];
        }
        var step = (PopulationUtil.range.end - PopulationUtil.range.start) / (count - 1);
        for (var i = count - 1; i >= 0; i--) {
            var offset = population - (PopulationUtil.range.start + i * step);
            if (offset >= 0) {
                return z.util.color.mix(colors[i], colors[i + 1], offset / step);
            }
        }
        return colors[count - 1];
    },

    appendRangeLegend: function (styles, parent) {
        var rangeGradients = "linear-gradient(";
        (z.util.mergeArray([], PopulationUtil.range.colors).reverse()).forEach(function (color) {
            rangeGradients += color + ","
        })
        rangeGradients = rangeGradients.substring(0, rangeGradients.length - 1)
        rangeGradients += ")";
        styles = z.util.mergeObject({
            "position": "absolute",
            "right": "10px",
            "bottom": "10px",
            "display": "flex",
            "flex-direction": "column",
            "align-items": "flex-end"
        }, styles)
        var rangeDiv = z.dom.create("div", {style: styles});
        z.dom.appendText(rangeDiv, PopulationUtil.range.end.toLocaleString());
        rangeDiv.appendChild(z.dom.create("<div style='background-image: " + rangeGradients + ";width: 20px;height: 130px'></div>"));
        z.dom.appendText(rangeDiv, PopulationUtil.range.start.toLocaleString());
        (parent || document.body).appendChild(rangeDiv);
        return rangeDiv;
    }
}