from collections import OrderedDict

from bookstack import Bookstack
from vcinema_utils import VCinemaUtils

# Page ID of https://wiki.jacknet.io/books/vcinema/page/films-by-release-year
PAGE_ID = 24


def get_films_by_year(viewings):
    viewings_filtered_by_year = VCinemaUtils.filter_viewings(viewings, "year")

    return viewings_filtered_by_year


def update_page(token_id, token_secret, films_by_year):
    page = build_page(films_by_year)
    Bookstack.update_page(VCinemaUtils.JACKNET_WIKI_URL, token_id, token_secret, PAGE_ID, markdown=page)


def build_page(films_by_year):
    films_by_year_sorted = OrderedDict(sorted(films_by_year.items(), key=lambda t: t[0], reverse=True))

    page = "| Year | Films |\n| - | - |"

    for year in films_by_year_sorted.keys():
        page += "\n"

        row_data = []
        row_data.append(str(year))
        row_data.append(VCinemaUtils.get_film_list(films_by_year_sorted[year]))

        page += " | ".join(row_data)

    return page
