import asyncio
import glob
from io import BytesIO
from quart import Blueprint, request, send_file
from matplotlib import pyplot as plt
from CONSTANT import DATA_BASEPATH
from modules.radar.allw_amplitude import radar_allw_amplitude
from modules.radar.allw_plot_heatmap import radar_all_heatmap_plot
from quart.utils import run_sync

BASE_PATH_RADAR = DATA_BASEPATH.radar
globed_all_files = glob.glob(f"{BASE_PATH_RADAR}/**/**.txt", recursive=True)


radar_module = Blueprint("Radar", __name__)


@radar_module.route("/metadata")
def get_all_files():
    return radar_allw_amplitude.get_all_pathes()


@radar_module.route("/metadata/models")
def get_all_models():
    return radar_allw_amplitude.get_all_models()


@radar_module.route('/render/heatmap')
async def render_v1():
    """
        wind_type: Any,
    year: Any,
    H: Any,
    model_name: Any
    """
    wind_type = request.args.get('wind_type')
    year = request.args.get('year')
    H = request.args.get('H')
    station = request.args.get('station')

    model_name = request.args.get('model_name')
    mode = request.args.get('mode')

    renderer = await run_sync(radar_allw_amplitude)(int(H), int(year), station, wind_type)
    if mode == "day":
        day = request.args.get('day')
        renderer.render_day(day, model_name)
    elif mode == "month":
        month = request.args.get('month')
        renderer.render_month(int(month), model_name)
    elif mode == "year":
        renderer.render_year(model_name)
    else:
        raise ValueError("mode not supported")
    buf = BytesIO()
    plt.savefig(buf, format='png')
    buf.seek(0)
    # close the plot
    plt.close()
    return await send_file(buf, mimetype='image/png')


@radar_module.route('/render/changes')
async def render_v2():
    """
    year: Any,
    station: Any,
    model_name: Any
    """
    year = request.args.get('year')
    station = request.args.get('station')
    model_name = request.args.get('model_name')
    start_month = request.args.get('start_month')
    end_month = request.args.get('end_month')
    if start_month is not None and end_month is not None:
        start_month = int(start_month)
        end_month = int(end_month)
        month_range = (start_month, end_month)
    else:
        month_range = (1, 12)

    buffer = await run_sync(radar_all_heatmap_plot)(int(year), station, model_name, month_range)
    buffer.seek(0)

    return await send_file(buffer, mimetype='image/png')
