import typing

import dominate.tags as tags

from . import feed

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_view(feeds: list[feed.Feed]) -> tags.html:
    document = tags.html(
        _standard_header("Subscribed Feeds"),
        tags.h1("Feeds"),
        tags.div(
            tags.form(
                {"method": "post", "action": "/refresh"},
                tags.input_(type="submit", value="Refresh"),
            ),
            tags.form(
                {"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": "feed"},
                    tags.h2(tags.a(f.title, href=f.link, target="_blank")),
                    (
                        tags.ul(
                            tags.li(
                                {"class": "entry"},
                                tags.a(
                                    entry.title, href=entry.link, target="_blank"
                                ),
                                f" ({entry.time_ago()})",
                            )
                            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
