import base64
from collections import Counter, OrderedDict
import csv
import os
from wand.image import Image
import worldmap
import warnings

from bookstack import Bookstack
from vcinema_utils import VCinemaUtils

warnings.filterwarnings("ignore")

# Page ID of https://wiki.jacknet.io/books/vcinema/page/films-by-country
PAGE_ID = 34


def get_films_by_country(viewings):
    viewings_filtered_by_country = VCinemaUtils.filter_viewings(viewings, "countries")

    if "Czechia" in viewings_filtered_by_country.keys():
        viewings_filtered_by_country["Czech Republic"] = viewings_filtered_by_country["Czechia"]
        viewings_filtered_by_country.pop("Czechia")

    return viewings_filtered_by_country


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


def build_page(films_by_country):
    table = build_table(films_by_country)

    country_counter = Counter(films_by_country)
    png_data = draw_map(country_counter)
    encoded = base64.b64encode(png_data).decode("utf-8")
    image = "![](data:image/png;base64,{})".format(encoded)
    page = image + "\n" + table

    return page


def get_flags_dict():
    flags = {}

    with open('country-flags.csv', newline='') as f:
        reader = csv.reader(f, quotechar="\"")
        next(reader, None)  # skip the headers

        for row in reader:
            flags[row[0]] = row[1]

    return flags


def build_table(films_by_country):
    films_by_country_sorted = OrderedDict(sorted(films_by_country.items(), key=lambda t: t[0]))

    flags = get_flags_dict()

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

    for country, films in films_by_country_sorted.items():
        table += "\n"

        row_data = []

        country_label = country
        if country in flags.keys():
            country_label += " "
            country_label += flags[country]

        row_data.append(country_label)
        row_data.append(VCinemaUtils.get_film_list(films))

        table += " | ".join(row_data)

    return table


def draw_map(films_by_country, file_name="vcinema_map.svg"):
    counter = Counter(films_by_country)
    countries = [k for k, v in counter.items()]
    counts = [len(v) for _, v in counter.items()]

    max_count = max(counts)

    opacity = [0.5 + (x / (float(max_count))/2.0) for x in counts]

    worldmap.plot(countries, cmap=["#FF4000"], opacity=opacity, filename=file_name, verbose=False)

    with Image(filename=file_name, width=1000, height=655) as i:
        png_data = i.make_blob("png")

    os.remove(file_name)

    return png_data
