export const sleep = (delay) =>
    new Promise((resolve) => setTimeout(resolve, delay));

export const onIdle = () =>
    new Promise((resolve) => requestIdleCallback(resolve));

export const resolveImage = (src) =>
    new Promise((resolve) => {
        const image = new Image();
        image.src = src;
        image.onload = () => resolve({ image, src });
    });

export const genStopsMap = (_stops) => {
    const stopsMap = new Map();
    let recentZoom = 20;
    let recentScale = stopsMap.get(recentZoom);
    const stops = [].concat(_stops);
    stops.sort((a, b) => b[0] - a[0]);
    stops.forEach((item, index) => {
        const curZoom = item[0];
        const curScale = item[1];
        let diffZoom = parseInt(recentZoom - curZoom);
        if (index == 0) {
            // 补上前面部分
            stopsMap.set(20, curScale);
            while (diffZoom) {
                stopsMap.set(20 - diffZoom, curScale);
                diffZoom--;
            }
        } else {
            // 计算中间部分插值
            let diffScale = recentScale - curScale;
            let scaleStep = diffScale / diffZoom;
            while (diffZoom) {
                stopsMap.set(
                    recentZoom - diffZoom,
                    recentScale - scaleStep * diffZoom
                );
                diffZoom--;
            }
        }
        recentZoom = curZoom;
        recentScale = stopsMap.get(recentZoom);
    });
    // 补上最后部分
    let lastZoom = stops[stops.length - 1][0];
    if (lastZoom !== 0) {
        while (lastZoom >= 0) {
            stopsMap.set(lastZoom, recentScale);
            lastZoom--;
        }
    }

    return stopsMap;
};
