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

from CONSTANT import DATA_BASEPATH
from modules.cosmic.gravityw_multiday import GravityMultidayPlot
from modules.cosmic.gravityw_perday import CosmicGravitywPlot
from modules.cosmic.planetw_daily import cosmic_planetw_daily_plot
from quart.utils import run_sync

from modules.cosmic.planetw_daily_process import cosmic_planet_daily_process
from modules.cosmic.planetw_perday import cosmic_planetw_plot_perday


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():
    year = request.args.get("year", 2008)
    T = request.args.get("T", 16)
    k = request.args.get("k", 1)
    target_h = request.args.get("target_h", 100)
    target_latitude = request.args.get("target_lat", 30)

    # path: str = f"{DATA_BASEPATH.cosmic}/cosmic.txt"
    temp_df = await run_sync(cosmic_planet_daily_process)(
        year=int(year),
        target_h=int(target_h),
        target_latitude=int(target_latitude)
    )

    await run_sync(cosmic_planetw_daily_plot)(
        temp_df,
        T=int(T),
        k=int(k)
    )
    buf = BytesIO()

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


@cosmic_module.route('/render/planet_wave/perday')
async def render_by_mode_single():
    year = request.args.get("year", 2008)
    T = request.args.get("T", 16)
    target_h = request.args.get("target_h", 40)
    target_latitude = request.args.get("target_lat", 30)
    start_day = request.args.get("start_day", 0)

    # path: str = f"{DATA_BASEPATH.cosmic}/cosmic.txt"
    temp_df = await run_sync(cosmic_planet_daily_process)(
        year=int(year),
        target_h=int(target_h),
        target_latitude=int(target_latitude)
    )

    await run_sync(cosmic_planetw_plot_perday)(
        temp_df,
        T=int(T),
        start_day=int(start_day)
    )
    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")
    lat_range = request.args.get("lat_range", "30.0 ~ 40.0")
    lat_range = tuple(map(float, lat_range.split("~")))

    p: CosmicGravitywPlot = await run_sync(CosmicGravitywPlot)(
        year=int(year), day=int(day), lat_range=lat_range)
    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)()
    elif mode == 'residual_mean':
        await run_sync(p.plot_results_residuals_means)()
    elif mode == 'background_temp':
        await run_sync(p.plot_results_background_temp)()
    else:
        raise ValueError("Invalid mode")

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

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


@cosmic_module.route("/render/gravity_wave/multiday")
async def multiday_render():
    year = request.args.get("year", 2008)
    start_day = request.args.get("start_day", 1)
    end_day = request.args.get("end_day", 365)
    mode = request.args.get("mode", "位温分布")
    lat_range = request.args.get("lat_range", "30.0 ~ 40.0")
    lat_range = tuple(map(float, lat_range.split("~")))

    p: GravityMultidayPlot = await run_sync(GravityMultidayPlot)(
        year=int(year),
        day_range=(start_day, end_day),
        lat_range=lat_range
    )
    if mode == "浮力频率均值":
        await run_sync(p.plot_heatmap_tempNz)()
    elif mode == "不同高度下的逐日统计分析":
        await run_sync(p.plot_heatmap_tempPtz)()
    elif mode == "每月浮力频率变化趋势":
        await run_sync(p.plot_floatage_trend)()
    elif mode == "每月平均重力势能的折线图":
        await run_sync(p.plot_monthly_energy)()
    elif mode == "每月平均N^2的折线图":
        await run_sync(p.plot_monthly_tempNz)()
    else:
        raise ValueError("Invalid mode")

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

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