import types
from typing import Iterator


def html_table(dictset: Iterator[dict], limit: int = 5):
    """
    Render the dictset as a HTML table.

    NOTE:
        This exhausts generators so is only recommended to be used on lists.

    Parameters:
        dictset: iterable of dictionaries
            The dictset to render
        limit: integer (optional)
            The maximum number of record to show in the table, defaults to 5

    Returns:
        string (HTML table)
    """

    def _to_html_table(data, columns):

        yield '<table class="table table-sm">'
        for counter, record in enumerate(data):
            if counter == 0:
                yield '<thead class="thead-light"><tr>'
                for column in columns:
                    yield "<th>" + column + "<th>\n"
                yield "</tr></thead><tbody>"

            if (counter % 2) == 0:
                yield '<tr style="background-color:#F4F4F4">'
            else:
                yield "<tr>"
            for column in columns:
                yield "<td>" + str(record.get(column)) + "<td>\n"
            yield "</tr>"

        yield "</tbody></table>"

    rows = []
    columns = []  # type:ignore
    for i, row in enumerate(dictset):
        rows.append(row)
        columns = columns + list(row.keys())
        if (i + 1) == limit:
            break
    columns = set(columns)  # type:ignore


    footer = ""
    if isinstance(dictset, types.GeneratorType):
        footer = f"\n<p>top {limit} rows x {len(columns)} columns</p>"
        footer += "\nNOTE: the displayed records have been spent"
    if isinstance(dictset, list):
        footer = f"\n<p>{len(dictset)} rows x {len(columns)} columns</p>"

    return "".join(_to_html_table(rows, columns)) + footer