import GeoJSON from '../src/ol/format/GeoJSON.js';
import Map from '../src/ol/Map.js';
import OSM from '../src/ol/source/OSM.js';
import Projection from '../src/ol/proj/Projection.js';
import VectorTileSource from '../src/ol/source/VectorTile.js';
import View from '../src/ol/View.js';
import {
  Tile as TileLayer,
  VectorTile as VectorTileLayer,
} from '../src/ol/layer.js';

// Converts geojson-vt data to GeoJSON
const replacer = function (key, value) {
  if (value.geometry) {
    let type;
    const rawType = value.type;
    let geometry = value.geometry;

    if (rawType === 1) {
      type = 'MultiPoint';
      if (geometry.length == 1) {
        type = 'Point';
        geometry = geometry[0];
      }
    } else if (rawType === 2) {
      type = 'MultiLineString';
      if (geometry.length == 1) {
        type = 'LineString';
        geometry = geometry[0];
      }
    } else if (rawType === 3) {
      type = 'Polygon';
      if (geometry.length > 1) {
        type = 'MultiPolygon';
        geometry = [geometry];
      }
    }

    return {
      'type': 'Feature',
      'geometry': {
        'type': type,
        'coordinates': geometry,
      },
      'properties': value.tags,
    };
  } else {
    return value;
  }
};

const map = new Map({
  layers: [
    new TileLayer({
      source: new OSM(),
    }),
  ],
  target: 'map',
  view: new View({
    center: [0, 0],
    zoom: 2,
  }),
});

const url = 'data/geojson/countries.geojson';
fetch(url)
  .then(function (response) {
    return response.json();
  })
  .then(function (json) {
    const tileIndex = geojsonvt(json, {
      extent: 4096,
      debug: 1,
    });
    const vectorSource = new VectorTileSource({
      format: new GeoJSON({
        // Data returned from geojson-vt is in tile pixel units
        dataProjection: new Projection({
          code: 'TILE_PIXELS',
          units: 'tile-pixels',
          extent: [0, 0, 4096, 4096],
        }),
      }),
      tileUrlFunction: function (tileCoord) {
        // Use the tile coordinate as a pseudo URL for caching purposes
        return JSON.stringify(tileCoord);
      },
    });
    // For tile loading obtain the GeoJSON for the tile coordinate
    // before calling the default tileLoadFunction
    const defaultTileLoadFunction = vectorSource.getTileLoadFunction();
    vectorSource.setTileLoadFunction(function (tile, url) {
      const tileCoord = JSON.parse(url);
      const data = tileIndex.getTile(tileCoord[0], tileCoord[1], tileCoord[2]);
      const geojson = JSON.stringify(
        {
          type: 'FeatureCollection',
          features: data ? data.features : [],
        },
        replacer
      );
      defaultTileLoadFunction(
        tile,
        'data:application/json;charset=UTF-8,' + geojson
      );
    });
    const vectorLayer = new VectorTileLayer({
      source: vectorSource,
    });
    map.addLayer(vectorLayer);
  });

@@ -1655,59 +1655,16 @@
 nst 
-vectorSource = new VectorTileSource(%7B%0A      
 format
-:
+ =
  new
@@ -1674,18 +1674,16 @@
 oJSON(%7B%0A
-  
       //
@@ -1742,18 +1742,16 @@
 s%0A      
- 
- 
 dataProj
@@ -1783,18 +1783,16 @@
         
-  
 code: 'T
@@ -1812,18 +1812,16 @@
         
- 
- 
 units: '
@@ -1834,18 +1834,16 @@
 ixels',%0A
-  
         
@@ -1878,25 +1878,69 @@
     
+  %7D),%0A
     %7D)
-,
+;
 %0A    
-  %7D),
+const vectorSource = new VectorTileSource(%7B
 %0A   
@@ -2113,239 +2113,28 @@
     
-%7D);%0A    // For tile loading obtain the GeoJSON for the tile coordinate%0A    // before calling the default tileLoadFunction%0A    const defaultTileLoadFunction = vectorSource.getTileLoadFunction();%0A    vectorSource.setTileLoadFunction(
+  tileLoadFunction: 
 func
@@ -2148,24 +2148,26 @@
 ile, url) %7B%0A
+  
       const 
@@ -2195,16 +2195,18 @@
 e(url);%0A
+  
       co
@@ -2277,16 +2277,18 @@
 rd%5B2%5D);%0A
+  
       co
@@ -2325,18 +2325,22 @@
         
-%7B%0A
+  %7B%0A  
         
@@ -2368,16 +2368,18 @@
 ction',%0A
+  
         
@@ -2421,24 +2421,26 @@
 %5B%5D,%0A        
+  
 %7D,%0A        r
@@ -2438,16 +2438,18 @@
         
+ 
+ 
 replacer
@@ -2451,24 +2451,26 @@
 lacer%0A      
+  
 );%0A      def
@@ -2470,112 +2470,249 @@
     
+  
-defaultTileLoadFunction(%0A        tile,%0A        'data:application/json;charset=UTF-8,' + geojson
+const features = format.readFeatures(geojson, %7B%0A          extent: vectorSource.getTileGrid().getTileCoordExtent(tileCoord),%0A          featureProjection: map.getView().getProjection()%0A        %7D);%0A        tile.setFeatures(features);
 %0A      
-);
+%7D,
 %0A   

read and set features in custom tileLoadFunction