from collections import OrderedDict
import string

from bookstack import Bookstack
from vcinema_utils import VCinemaUtils

# Page ID of https://wiki.jacknet.io/books/vcinema/page/references
PAGE_ID = 62


def get_films_by_reference(viewings):
    viewings_filtered_by_keyword = VCinemaUtils.filter_viewings(viewings, "keywords")
    viewings_filtered_by_reference_keyword = {k: v for k, v in viewings_filtered_by_keyword.items() if k.startswith("reference-to")}

    return viewings_filtered_by_reference_keyword


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


def build_page(films_by_reference_keyword):
    reference_keywords_sorted = OrderedDict(sorted(films_by_reference_keyword.items(), key=lambda t: t[0]))

    table = "| Referenced | Films |\n| - | - |"

    for year in reference_keywords_sorted.keys():
        table += "\n"

        row_data = []
        row_data.append(str(string.capwords(year[13:].replace("-", " "))))
        row_data.append(VCinemaUtils.get_film_list(reference_keywords_sorted[year]))

        table += " | ".join(row_data)

    return table
