from flask import Blueprint, Flask, render_template, url_for


def _build_test_app():
    app = Flask(
        __name__,
        template_folder="../templates",
    )
    app.jinja_env.globals["csrf_token"] = lambda: ""
    app.jinja_env.filters["number_format"] = lambda value: f"{value:,}"

    edm = Blueprint("edm", __name__)

    for endpoint, path in {
        "edm_dashboard": "/edm",
        "festival_dashboard": "/festival",
        "mothers_day_dashboard": "/mothers_day",
        "valentine_520_dashboard": "/valentine_520",
        "labor_day_dashboard": "/labor_day",
    }.items():
        edm.add_url_rule(path, endpoint, lambda: "")

    app.register_blueprint(edm)
    return app


def test_edm_dashboard_sort_links_use_blueprint_endpoint():
    app = _build_test_app()
    page_paths = {
        "edm": "/edm",
        "festival": "/festival",
        "mothers_day": "/mothers_day",
        "valentine_520": "/valentine_520",
        "labor_day": "/labor_day",
    }

    with app.test_request_context("/edm"):
        promo_pages = [
            {
                "url": url_for(f"edm.{page}_dashboard"),
                "name": page,
                "id": page,
            }
            for page in page_paths
        ]

        for page, path in page_paths.items():
            html = render_template(
                "edm_dashboard.html",
                promo_pages=promo_pages,
                current_promo_page=page,
                page_title=page,
                activity_time="",
                last_update="",
                total_edm_products=0,
                scheduler_stats={},
                slot_stats={
                    "10:00": {
                        "on_shelf": 0,
                        "new": 0,
                        "up": 0,
                        "down": 0,
                    }
                },
                grouped_items={"10:00": []},
                active_tab="10:00",
                current_sort="default",
                current_order="desc",
                slugify=lambda value: value.replace(":", ""),
                datetime_now="",
                metabase_url="",
                grist_url="",
            )

            assert f'{path}?sort_by=name&amp;order=desc' in html
            assert f'{path}?sort_by=price&amp;order=desc' in html

            if page == "edm":
                assert f'{path}?sort_by=remain_qty&amp;order=desc' in html
