from io import BytesIO
from quart import Blueprint, request, send_file
from matplotlib import pyplot as plt

from modules.cosmic.gravityw_perday import CosmicGravitywPlot
from modules.cosmic.planetw_daily import cosmic_planetw_daily_plot
from quart.utils import run_sync


cosmic_module = Blueprint("Cosmic", __name__)


@cosmic_module.route('/metadata')
def get_meta():
    return []


@cosmic_module.route('/render/planet_wave/daily')
@cosmic_module.route('/temp_render')
async def render():
    T = request.args.get("T", 16)
    await run_sync(cosmic_planetw_daily_plot)(T=int(T))
    buf = BytesIO()

    plt.savefig(buf, format="png")
    buf.seek(0)
    return await send_file(buf, mimetype="image/png")


@cosmic_module.route('/render/gravity_wave/perday')
@cosmic_module.route('/render/single')
async def single_render():
    year = request.args.get("year", 2008)
    day = request.args.get("day", 1)
    mode = request.args.get("mode", "mean_ktemp_Nz")

    p: CosmicGravitywPlot = await run_sync(CosmicGravitywPlot)(year=int(year), day=int(day))
    if mode == "mean_ktemp_Nz":
        await run_sync(p.plot_results_mean_ktemp_Nz)()
    elif mode == "mean_ktemp_Ptz":
        await run_sync(p.plot_results_mean_ktemp_Ptz)()
    else:
        raise ValueError("Invalid mode")

    buf = BytesIO()
    plt.savefig(buf, format="png")
    buf.seek(0)

    return await send_file(buf, mimetype="image/png")
