"""Routes word clouds."""
import json, textwrap, io, surveyparser, readingparser, pandas
import matplotlib
import wordcloud
from bottle import Bottle, route, view, response, request, abort

matplotlib.use("SVG")
cloud = Bottle()

@cloud.route("/surveys/<name>/reading/<number>/cloud.png")
def generate_cloud(name, number):
    survey, _ = surveyparser.get_survey(name)

    # Filter survey
    if request.query.get("selected_answers"):
        selected_answers = json.loads(request.query.get("selected_answers"))
        survey = surveyparser.filter_survey(survey,  surveyparser.get_metadata(name), selected_answers)

    readings = surveyparser.get_readings(name)
    if readings[int(number)]["type"] == "cloud":
        fig, ax = matplotlib.pyplot.subplots()

        fig.figsize = (100, 100)

        stopwords = set(line.strip() for line in open("static/stopwords.txt"))
        stopwords.update(set(readings[int(number)]["words"].split(","))) # TODO Remove spaces in-between

        text = " ".join(comment for comment in survey[readings[int(number)]["question"]])
        word_cloud = wordcloud.WordCloud(
            font_path="/usr/share/fonts/cantarell/Cantarell-Regular.otf",
            width = 1000,
            height = 1000,
            min_font_size = 8,
            random_state = 1,
            background_color = "white",
            collocations = True,
            collocation_threshold = 1,
            colormap = "Set1",
            stopwords = stopwords,
            max_words=30,
            min_word_length=3,
        ).generate(text)

        ax.imshow(word_cloud, interpolation = "bilinear")
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
        ax.spines["top"].set_visible(False)
        ax.spines["right"].set_visible(False)
        ax.spines["bottom"].set_visible(False)
        ax.spines["left"].set_visible(False)

        # Output to object
        output = io.BytesIO()
        fig.savefig(output, format = "svg", dpi = 1200, bbox_inches = "tight")
        response.content_type = "image/svg+xml"

        return output.getvalue()

    # Respond 501 otherwise as only cloud readings can be rendered into cloud words
    else:
        return abort(501)
