#!/bin/bash

# Quantization
QU=1e4

rm -rvf madrid
mkdir -p build madrid

curl -o build/Sec_2017.7z -C - 'https://www.madrid.es/UnidadesDescentralizadas/UDCEstadistica/Nuevaweb/Territorio,%20Clima%20y%20Medio%20Ambiente/Territorio/Cartograf%C3%ADa/Ficheros%20Division%20Administrativa/Ficheros%20de%20Divisi%C3%B3n%20Administrativa.%20Sistema%20de%20referencia%20ETRS89/Secciones/Vigente/Sec_2017.7z'
7z e -obuild build/Sec_2017.7z -aoa

geo2topo -n census_tracts=<( \
    shp2json build/Secciones.shp \
      | geoproject 'd3.geoIdentity().reflectY(true).fitSize([960, 600], d)' \
      | ndjson-split 'd.features' \
      | ndjson-map '(d.id = d.properties.CODSECCION, d)') \
  | topomerge neighborhoods=census_tracts -k 'd.properties.CODBAR' \
  | topomerge districts=neighborhoods -k 'd.properties.CODDIS' \
  | topomerge city=districts \
  > madrid/census_tracts.json

# Inspired by: https://bl.ocks.org/mbostock/39b34968ad5eab65de1d7da81f78bb27
# Re-compute the topology as a further optimization.
# This consolidates unique sequences of arcs.
# https://github.com/topojson/topojson-simplify/issues/4
topo2geo -n \
  < madrid/census_tracts.json \
  census_tracts=madrid/_census_tracts.json \
  neighborhoods=madrid/_neighborhoods.json \
  districts=madrid/_districts.json \
  city=madrid/_city.json

geo2topo -n \
  census_tracts=<( \
      cat madrid/_census_tracts.json \
        | ndjson-map '(delete d.properties, d)') \
  neighborhoods=<( \
      cat madrid/_neighborhoods.json \
        | ndjson-map '(delete d.properties, d)') \
  districts=<( \
      cat madrid/_districts.json \
        | ndjson-map '(delete d.properties, d)') \
  city=<( \
      cat madrid/_city.json \
        | ndjson-map '(delete d.properties, d)') \
  | topoquantize $QU \
  > madrid/census_tracts.json

rm madrid/_census_tracts.json madrid/_neighborhoods.json madrid/_districts.json madrid/_city.json
