class TileUpdater {
    constructor(map) {
        this.map = map;
        this.updateInterval = 100; // 100ms更新一次
        this.startUpdates();
    }

    async checkForChanges() {
        try {
            const response = await fetch('/check_changes');
            const changes = await response.json();

            if (changes.length > 0) {
                this.updateChangedTiles(changes);
            }
        } catch (error) {
            console.error('检查瓦片更新失败:', error);
        }
    }

    updateChangedTiles(changes) {
        changes.forEach(change => {
            const coords = change.coords;
            const tileUrl = `http://localhost:5000/tiles/${coords.z}/${coords.x}_${coords.y}.png`;

            this.map.eachLayer(layer => {
                if (layer instanceof L.TileLayer) {
                    const tile = layer._tiles[`${coords.z}/${coords.x}/${coords.y}`];
                    if (tile) {
                        // 强制重新加载瓦片
                        tile.el.src = tileUrl + '?t=' + new Date().getTime();
                    }
                }
            });
        });
    }

    startUpdates() {
        setInterval(() => this.checkForChanges(), this.updateInterval);
    }
}

// 导出类
window.TileUpdater = TileUpdater; 