"""Generate the figures with Python 3 and matplotlib. Source geometry: GeoDa Center."""
import csv
import io
import json
import zipfile
from pathlib import Path
from urllib.request import urlopen

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.patches import Polygon

ROOT = Path(__file__).resolve().parent
URL = "https://geodacenter.github.io/data-and-lab/data/guerry.zip"
COLORS = ["#dce9dc", "#a8cbb8", "#6ba493", "#357b72", "#174e51"]
with (ROOT / "guerry.csv").open(encoding="utf-8", newline="") as stream:
    rows = list(csv.DictReader(stream))
by_id = {int(row["dept"]): row for row in rows}
with urlopen(URL, timeout=25) as response:
    archive = zipfile.ZipFile(io.BytesIO(response.read()))
geo = json.loads(archive.read("guerry/guerry.geojson"))
assert set(by_id) - {200} == {int(f["properties"]["dept"]) for f in geo["features"]}
plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 11, "svg.fonttype": "none",
                     "axes.edgecolor": "#899a92", "text.color": "#183a39", "axes.labelcolor": "#183a39"})
fig, ax = plt.subplots(figsize=(6.2, 5.7))
patches, fills = [], []
anchors = {}
for feature in geo["features"]:
    info, geometry = feature["properties"], feature["geometry"]
    row = by_id[int(info["dept"])]
    assert all(int(row[k]) == int(info[v]) for k, v in
               [("Crime_prop", "Crm_prp"), ("Crime_pers", "Crm_prs"), ("Literacy", "Litercy")])
    rate = 100000 / int(row["Crime_prop"])
    colour = COLORS[sum(rate >= threshold for threshold in (10, 15, 20, 30))]
    polygons = geometry["coordinates"] if geometry["type"] == "MultiPolygon" else [geometry["coordinates"]]
    for polygon in polygons:
        ring = polygon[0]
        patches.append(Polygon(ring, closed=True))
        fills.append(colour)
    if row["Department"] in ("Seine", "Creuse"):
        ring = max(polygons, key=lambda p: len(p[0]))[0]
        anchors[row["Department"]] = tuple((min(v) + max(v)) / 2 for v in zip(*ring))
ax.add_collection(PatchCollection(patches, facecolors=fills, edgecolors="white", linewidths=0.65))
ax.autoscale_view()
ax.set_aspect("equal")
ax.axis("off")
for name, offset in [("Seine", (43, 22)), ("Creuse", (-31, -30))]:
    x, y = anchors[name]
    ax.plot(x, y, "o", ms=4, color="#9d411f", zorder=3)
    ax.annotate(name, (x, y), xytext=offset, textcoords="offset points",
                fontsize=11, fontweight="bold", ha="center", va="center",
                bbox={"boxstyle":"round,pad=0.25", "facecolor":"#fffaf1","edgecolor":"none"},
                arrowprops={"arrowstyle":"-", "color":"#9d411f", "lw":1})
fig.savefig(ROOT / "karte.svg", transparent=True, bbox_inches="tight", pad_inches=0.02)
plt.close(fig)

for field, filename in [("Crime_prop","eigentum.svg"), ("Crime_pers","personen.svg")]:
    fig, ax = plt.subplots(figsize=(5.3, 3.9))
    x = [int(r["Literacy"]) for r in rows]
    y = [100000/int(r[field]) for r in rows]
    ax.scatter(x, y, s=34, color="#296f68", edgecolor="white", linewidth=.4, alpha=.83)
    index = next(i for i,r in enumerate(rows) if r["Department"] == "Seine")
    ax.scatter(x[index], y[index], marker="D", color="#9d411f", s=43)
    ax.annotate("Seine", (x[index],y[index]), xytext=(-9,4), textcoords="offset points",
                ha="right", fontsize=10, color="#893c21")
    ax.set(xlim=(0, 80), ylim=(0, 80), xlabel="Lesen und Schreiben bei Rekruten (%)",
           ylabel="Angeklagte je 100 000 Einwohner")
    ax.set_xticks([0,20,40,60,80]); ax.set_yticks([0,20,40,60,80])
    ax.grid(axis="y",color="#d4ded8",lw=.7); ax.set_axisbelow(True)
    ax.spines[["right","top"]].set_visible(False)
    fig.tight_layout()
    fig.savefig(ROOT / filename, transparent=True)
    plt.close(fig)
