from typing import List, Optional

from annoying.decorators import render_to
from django.http import HttpRequest, HttpResponseRedirect

from demonstration.forms import SearchForm, PersonForm, UploadForm

NAMES: List[str] = [
    "Jean",
    "Paul",
    "Robert",
    "Julien",
    "Nicolas",
    "François",
    "Julie",
    "Marie",
    "Anne",
    "Évelyne",
    "Jeanne",
    "Claire",
]


@render_to("demonstration/index.html")
def view_index(request: HttpRequest):  # noqa
    return {}


@render_to("demonstration/search_form_view.html")
def view_search_form(request: HttpRequest):  # noqa
    """
    View for the search form.

    Args:
        request: HTTP request.

    Returns:
        Data for rendering the template, as a context dictionary.

    """
    form = SearchForm(request.GET) if request.GET else SearchForm()
    results: List[str] = []
    if form.is_valid():
        query: str = form.cleaned_data["query"].lower()
        results = [item for item in NAMES if query in item.lower()]
    return {"form": form, "results": results}


@render_to("demonstration/person_form_view.html")
def view_person_form(request: HttpRequest):  # noqa
    """
    View for the person form.

    Args:
        request: HTTP request.

    Returns:
        Data for rendering the template, as a context dictionary.

    """
    form = PersonForm(request.POST) if request.method == "POST" else PersonForm()
    return {"form": form}


@render_to("demonstration/upload_form_view.html")
def view_upload_form(request: HttpRequest):  # noqa
    """
    View for the upload form.

    Args:
        request: HTTP request.

    Returns:
        Data for rendering the template, as a context dictionary.

    """
    form = UploadForm(request.POST, request.FILES) if request.method == "POST" else UploadForm()
    image_url: Optional[str] = None
    if form.is_valid():
        image_url = form.save_uploaded_file(request)
    return {"form": form, "image_url": image_url}
