import typing

import dominate.tags as tags

from . import feed


class time_(tags.html_tag):
    """The <time> HTML element represents a specific period in time. It may
    include the datetime attribute to translate dates into machine-readable
    format, allowing for better search engine results or custom features such
    as reminders.

    It may represent one of the following:

    - A time on a 24-hour clock.
    - A precise date in the Gregorian calendar (with optional time and timezone information).
    - A valid time duration.
    """

    pass


def _standard_header(title: str) -> tags.head:
    head = tags.head(
        tags.meta(charset="utf8"),
        tags.title(title),
        tags.link(rel="stylesheet", href="/style.css", type="text/css"),
    )
    assert isinstance(head, tags.head)
    return head


def _feed_summary(f: feed.Feed) -> tags.li:
    if len(f.entries) == 0:
        last_entry = tags.p({"class": "feed-summary-entry"}, tags.i("Never posted"))
    else:
        entry = f.entries[0]
        last_entry = [
            tags.p(
                {"class": "feed-summary-timestamp"},
                tags.i(
                    f"Posted ",
                    time_(entry.time_ago(), datetime=entry.posted_time_iso()),
                    " ago",
                ),
            ),
            tags.p(
                {"class": "feed-summary-entry"},
                tags.a({"href": entry.link, "target": "_blank"}, entry.title),
            ),
        ]

    result = tags.li(
        {"class": "feed-summary"},
        # TODO: Image!
        tags.h2(
            {"class": "feed-summary-title"},
            tags.a(
                {"class": "feed-summary-feed-link", "href": f"#{f.meta.url}"},
                f.title,
            ),
        ),
        last_entry,
    )
    assert isinstance(result, tags.li)
    return result


def feed_view(feeds: list[feed.Feed]) -> tags.html:
    document = tags.html(
        _standard_header("Subscribed Feeds"),
        tags.body(
            {"class": "fv-body"},
            tags.h1({"class": "fv-title"}, "Feeds"),
            tags.form(
                {"class": "fv-subscribe", "method": "post", "action": "/subscribe"},
                tags.label({"for": "url"}, "Feed url:"),
                tags.input_(type="url", name="url"),
                tags.input_(type="submit", value="Subscribe"),
            ),
            tags.div(
                {"class": "fv-main-panel"},
                tags.div(
                    {"class": "fv-summary-panel"},
                    tags.form(
                        {
                            "class": "fv-summary-refresh",
                            "method": "post",
                            "action": "/refresh",
                        },
                        tags.input_(type="submit", value="Refresh"),
                    ),
                    tags.ul(
                        {"class": "fv-summary-list"},
                        (_feed_summary(f) for f in feeds),
                    ),
                ),
                tags.div(
                    {"class": "fv-feed-panel"},
                    (
                        tags.div(
                            {"class": "fv-feed"},
                            tags.h2(
                                {"class": "fv-feed-title", "id": f.meta.url},
                                tags.a(f.title, href=f.link, target="_blank"),
                            ),
                            (
                                tags.ul(
                                    tags.li(
                                        {"class": "entry"},
                                        tags.a(
                                            entry.title,
                                            href=entry.link,
                                            target="_blank",
                                        ),
                                        " ",
                                        time_(
                                            f"({entry.time_ago()})",
                                            datetime=entry.posted_time_iso(),
                                        ),
                                    )
                                    for entry in f.entries
                                )
                                if len(f.entries) > 0
                                else tags.i("No entries...")
                            ),
                        )
                        for f in feeds
                    ),
                ),
            ),
        ),
    )
    assert isinstance(document, tags.html)
    return document


def subscribe_choose_view(candidates: typing.Iterable[tuple[str, str]]) -> tags.html:
    document = tags.html(
        _standard_header("Choose Feed"),
        tags.h1("Choose Feed"),
        tags.p("More than one feed was found. Choose the feed to subscribe to."),
        tags.table(
            tags.caption("Potential feeds"),
            tags.thead(tags.tr(tags.th("Title"), tags.th("URL"), tags.th())),
            tags.tbody(
                tags.form(
                    {"action": "/subscribe", "method": "post"},
                    tags.tr(
                        tags.td(title),
                        tags.td(url),
                        tags.td(
                            tags.input_(
                                {"type": "hidden", "name": "url", "value": url}
                            ),
                            tags.input_({"type": "submit", "value": "Subscribe"}),
                        ),
                    ),
                )
                for title, url in candidates
            ),
        ),
    )
    assert isinstance(document, tags.html)
    return document
