/**
 * @classdesc
 * 自定义百度数据源-----胡红勋-----
 * @constructor
 * @extends {ol.source.XYZ}
 * @param 
 * @api
 */
import XYZ from 'ol/source/XYZ'
import TileImage from 'ol/source/TileImage'
import { inherits } from 'ol'
import TileGrid from 'ol/tilegrid/TileGrid'

function BaiDuSource(options = {
    origin: [43.88955327932, 12.590178885765]
}) {
    let attributions = options.attributions || 'www.baidu.com'
    let projection = options.projection || 'EPSG:3857'
    let crossOrigin = options.crossOrigin || 'anonymous'
    let url = options.url || 'http://online{0-3}.map.bdimg.com/onlinelabel/?qt=tile&x={x}&y={y}&z={z}&styles=pl&udt=20170607&scaler=1&p=1'
    let func = (tileCoord) => {
        var z = tileCoord[0]
        var x = tileCoord[1]
        var y = tileCoord[2]
        if (x < 0) {
            x = 'M' + (-x)
        }
        if (y < 0) {
            y = 'M' + (-y)
        }
        return url.replace('{0-3}', BaiDuSource.getRandom(0, 3)).replace('{x}', (x).toString()).replace('{y}', y.toString()).replace('{z}', (z).toString())
    }
    let tileUrlFunction = options.tileUrlFunction || func
    let levels = options['levels'] || 19
    var resolutions = []
    for (var z = 0; z < levels; z++) {
        resolutions[z] = Math.pow(2, levels - 1 - z)
    }
    var tileGrid = new TileGrid({
        tileSize: (options.tileSize || 256),
        origin: (options.origin || [0, 0]),
        extent: (options.extent || undefined),
        resolutions: resolutions,
        minZoom: ((options.minZoom && typeof options.minZoom === 'number') ? options.minZoom : 0)
    })
    TileImage.call(this, {
        tileGrid,
        attributions,
        cacheSize: options.cacheSize,
        projection,
        crossOrigin,
        opaque: options.opaque !== undefined ? options.opaque : true,
        maxZoom: options.maxZoom !== undefined ? options.maxZoom : 19,
        reprojectionErrorThreshold: options.reprojectionErrorThreshold,
        tileUrlFunction: tileUrlFunction,
        url: url,
        wrapX: options.wrapX
    })
}
inherits(BaiDuSource, TileImage)

/**
 * 获取随机服务器
 * @param min
 * @param max
 * @returns {number}
 */
BaiDuSource.getRandom = function(min, max) {
    var r = Math.random() * (max - min)
    var re = Math.round(r + min)
    re = Math.max(Math.min(re, max), min)
    return re
}

export default BaiDuSource