"""
Matplotlib output for CuraCourse code editors (code library file).

CuraCourse runs Python on a server with no display, so plt.show() has no
window to open. This module is a matplotlib backend: plt.show() prints each
open figure as <img src="data:image/png;base64,..."> (the code editor shows
that as an image) and closes it. Figures still open when the program ends
are printed too, so a program that forgets plt.show() still shows its plot.

plt.savefig("chart.png") (or fig.savefig) writes the file as usual and also
shows the figure, so students see what they saved. A figure is shown again
only if it changed since: saving it twice (say .png and .svg), or saving
then plt.show(), shows it once.
Saving to a file object (io.BytesIO, an open file) shows nothing.

Put this file and `matplotlibrc` in the code library. The matplotlibrc line
`backend: module://curacourse_plots` makes matplotlib load this module, so
student code stays standard:

    import matplotlib.pyplot as plt
    plt.plot([1, 2, 3], [4, 1, 9])
    plt.show()

If a program runs from another folder (matplotlibrc not found), it can opt in
with `import curacourse_plots` before importing pyplot.

"""

import atexit
import base64
import io
import os

import matplotlib
from matplotlib import _pylab_helpers
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.figure import Figure

DPI = 100  # 6.4x4.8 in default figure -> 640x480 PNG, ~20-60 KB

FigureCanvas = FigureCanvasAgg
FigureManager = FigureCanvasAgg.manager_class


_original_savefig = getattr(Figure.savefig, "_cc_original", Figure.savefig)


def _print_figure(figure):
    buf = io.BytesIO()
    _original_savefig(figure, buf, format="png", dpi=DPI, bbox_inches="tight")
    data = base64.b64encode(buf.getvalue()).decode("ascii")
    label = figure.get_label() or "Plot %s" % getattr(figure, "number", "")
    print('<img src="data:image/png;base64,%s" alt="%s">' % (data, label.replace('"', "'").strip()), flush=True)
    figure._cc_shown = True
    _mark_clean(figure)


def _mark_clean(figure):
    # Clear `stale` on every artist (saving can leave some stale), so the next
    # real change marks the figure stale again.
    for artist in figure.findobj():
        artist.stale = False


def _needs_showing(figure):
    return not getattr(figure, "_cc_shown", False) or figure.stale


def _savefig(self, fname, *args, **kwargs):
    """Figure.savefig, then show the figure when it was saved to a file path."""
    # Decide before saving: a save (another dpi, format or bbox) marks the
    # figure stale by itself, though nothing in it changed.
    needs_showing = _needs_showing(self)
    result = _original_savefig(self, fname, *args, **kwargs)
    if not needs_showing:
        _mark_clean(self)
    elif isinstance(fname, (str, os.PathLike)):
        _print_figure(self)
    return result


_savefig._cc_original = _original_savefig
_savefig.__doc__ = _original_savefig.__doc__
Figure.savefig = _savefig


def show(*args, **kwargs):
    """Print every open figure not already shown, then close them (like plt.show() in a script)."""
    for manager in _pylab_helpers.Gcf.get_all_fig_managers():
        if _needs_showing(manager.canvas.figure):
            _print_figure(manager.canvas.figure)
    _pylab_helpers.Gcf.destroy_all()


@atexit.register
def _show_unshown():
    show()


# `import curacourse_plots` also works when matplotlibrc is not picked up.
if __name__ != "__main__" and matplotlib.get_backend() != "module://curacourse_plots":
    matplotlib.use("module://curacourse_plots")
