from flask import Blueprint, render_template, request, abort
from flask_login import login_required

from app.services.permissions import require
from app.services import task_queries, listing
from config import TASK_CATEGORIES

bp = Blueprint("tasks", __name__, url_prefix="/tasks")
CATEGORY_MAP = {c["key"]: c for c in TASK_CATEGORIES}


@bp.route("/")
@login_required
@require("tasks")
def index():
    counts = task_queries.get_category_counts()
    return render_template("tasks/index.html", categories=TASK_CATEGORIES, counts=counts)


@bp.route("/<key>")
@login_required
@require("tasks")
def result(key):
    category = CATEGORY_MAP.get(key) or abort(404)
    search = request.args.get("q", "").strip()
    city = request.args.get("city") or None

    rows, total = task_queries.get_category_customers(
        key, search=search, city=city, limit=listing.page_limit()
    )
    return render_template("tasks/result.html", category=category, rows=rows, total=total,
                            cities=task_queries.get_category_cities(key),
                            q=request.args.get("q", ""), selected_city=city)
