#!/usr/bin/env python3

# Use the proper idiom in the main module ...
# NOTE: See https://docs.python.org/3.13/library/multiprocessing.html#the-spawn-and-forkserver-start-methods
if __name__ == "__main__":
    # Import standard modules ...
    import json
    import pathlib

    # Import special modules ...
    try:
        import cartopy
        cartopy.config.update(
            {
                "cache_dir" : pathlib.PosixPath("~/.local/share/cartopy").expanduser(),
            }
        )
    except:
        raise Exception("\"cartopy\" is not installed; run \"pip install --user Cartopy\"") from None
    try:
        import matplotlib
        matplotlib.rcParams.update(
            {
                       "axes.xmargin" : 0.01,
                       "axes.ymargin" : 0.01,
                            "backend" : "Agg",                                  # NOTE: See https://matplotlib.org/stable/gallery/user_interfaces/canvasagg.html
                         "figure.dpi" : 300,
                     "figure.figsize" : (9.6, 7.2),                             # NOTE: See https://github.com/Guymer/misc/blob/main/README.md#matplotlib-figure-sizes
                          "font.size" : 8,
                "image.interpolation" : "none",                                 # NOTE: See https://matplotlib.org/stable/gallery/images_contours_and_fields/interpolation_methods.html
                     "image.resample" : False,
            }
        )
        import matplotlib.pyplot
    except:
        raise Exception("\"matplotlib\" is not installed; run \"pip install --user matplotlib\"") from None
    try:
        import shapely
        import shapely.geometry
    except:
        raise Exception("\"shapely\" is not installed; run \"pip install --user Shapely\"") from None

    # Import my modules ...
    try:
        import pyguymer3
        import pyguymer3.geo
        import pyguymer3.image
    except:
        raise Exception("\"pyguymer3\" is not installed; run \"pip install --user PyGuymer3\"") from None

    # Set point ...
    point = (-1.463097, 52.915709)                                              # [°], [°]

    # Set number of bearings ...
    nAng = 361                                                                  # [#]

    # Create short-hand for the colour map ...
    cmap = matplotlib.colormaps["turbo"]

    # Load tile metadata ...
    with open("OrdnanceSurveyBackgroundImages/miniscale.json", mode = "rt", encoding = "utf-8") as fObj:
        meta = json.load(fObj)

    # **************************************************************************

    # Create figure ...
    fg = matplotlib.pyplot.figure(figsize = (7.2, 7.2))

    # Create axis ...
    ax = pyguymer3.geo.add_axis(
        fg,
        debug = False,
         dist = 20.0e3,
          lat = point[1],
          lon = point[0],
    )

    # Configure axis ...
    ax.set_title("Derby Train Station")

    # Initialize float and lists and draw data ...
    # NOTE: As of 5/Dec/2023, the default "zorder" of the coastlines is 1.5, the
    #       default "zorder" of the gridlines is 2.0 and the default "zorder" of
    #       the scattered points is 1.0.
    dist = 0.0                                                                  # [m]
    labels = []
    lines = []
    ax.scatter(
        [point[0]],
        [point[1]],
            alpha = 1.0,
        edgecolor = "none",
        facecolor = "red",
        transform = cartopy.crs.PlateCarree(),
           zorder = 5.0,
    )
    for i in range(6):
        dist += 2500.0                                                          # [m]
        ax.add_geometries(
            [pyguymer3.geo.buffer(shapely.geometry.Point(point[0], point[1]), dist, debug = False, nAng = nAng, simp = -1.0)],
            cartopy.crs.PlateCarree(),
            alpha = 1.0,
            edgecolor = cmap(float(i) / 5.0),
            facecolor = "none",
            linewidth = 1.0
        )
        labels.append(f"{0.001 * dist:.1f} km")
        lines.append(matplotlib.lines.Line2D([], [], color = cmap(float(i) / 5.0)))

    # Draw background image ...
    ax.imshow(
        matplotlib.pyplot.imread(f'OrdnanceSurveyBackgroundImages/{meta["MiniScale_(mono)_R22"]["greyscale"]}'),
             cmap = "gray",
           extent = meta["MiniScale_(mono)_R22"]["extent"],
           origin = "upper",
        transform = cartopy.crs.OSGB(),
             vmin = 0.0,
             vmax = 1.0,
    )

    # Configure axis ...
    ax.legend(
        lines,
        labels,
         loc = "upper right",
        ncol = 1,
    )

    # Configure figure ...
    fg.tight_layout()

    # Save figure ...
    fg.savefig("miniscale.png")
    matplotlib.pyplot.close(fg)

    # Optimize PNG ...
    pyguymer3.image.optimise_image("miniscale.png", strip = True)
