from flask import Flask, render_template, make_response
from flask_paginate import Pagination, get_page_parameter, get_page_args
from flask_caching import Cache
from flask import request
import pendulum
import subprocess
import base64
import os
base_path = "/messagebase"
app = Flask(__name__, static_url_path=base_path + "/static")
@app.template_filter("datefmt")
def format_datetime(value):
    dt = pendulum.from_timestamp(value, tz=pendulum.tz.local_timezone())
    return dt.to_datetime_string()
# Check Configuring Flask-Caching section for more details
# cache = Cache(app, config={"CACHE_TYPE": "filesystem", "CACHE_DIR": "cache"})
cache = Cache(app, config={"CACHE_TYPE": "redis", "CACHE_REDIS_HOST": "redis"})
# cache = Cache(app, config={"CACHE_TYPE": "redis", "CACHE_REDIS_HOST": "olympus"})
import jammin
bases = {
    "FSXNET-General": "msgs/fsx_gen",
    "FSXNET-BBS": "msgs/fsx_bbs",
    "FSXNET-BOT": "msgs/fsx_bot",
    "FSXNET-Magicka": "msgs/fsx_mag",
    "HappyNet-General": "msgs/hpy_gen",
}
# bases = {"FSX_BOT": "fsx_bot"}
# @cache.memoize(timeout=5 * 60, key_prefix="messages")
@cache.memoize(timeout=5 * 60)
def get_messages(base):
    messages = jammin.get_messages(base)
    messages.reverse()
    return messages
@cache.memoize(timeout=60)
def get_message(base, msgno):
    message = jammin.read_message(base, msgno)
    return message
@app.errorhandler(404)
def not_found(e):
    return render_template("404.html")
@app.route(base_path + "/list")
def list_bases():
    return render_template(
        "list.html", bases=bases, base_path=base_path, title="Message Areas"
    )
    # return 'Here would be a listing of message bases'
@app.route(base_path + "/clear")
def clear_cache():
    cache.clear()
    return "Cache Cleared.  Back to hitting refresh!"
@app.route(base_path + "/messages/")
def display_messages(area):
    if area not in bases:
        return render_template(
            "missing-area.html", base_path=base_path, title="Missing Area"
        )
    # messages = jammin.get_messages(bases[area])
    messages = get_messages(bases[area])
    # messages.reverse()  # cached.reverse()
    page = request.args.get(get_page_parameter(), type=int, default=1)
    # get_page_arg defaults to page 1, per_page of 10
    PER_PAGE = 50
    total = len(messages)
    pagination = Pagination(
        page=page,
        total=total,
        css_framework="foundation",
        record_name="messages",
        per_page=PER_PAGE,
    )
    page, per_page, offset = get_page_args()
    start = (page - 1) * PER_PAGE
    end = start + PER_PAGE
    # messages = messages[(page-1) * PER_PAGE:offset+PER_PAGE]
    messages = messages[start:end]
    return render_template(
        "messages.html",
        messages=messages,
        area=area,
        pagination=pagination,
        base_path=base_path,
        title="Messages for " + bases[area],
    )
@cache.memoize(timeout=60)
def ansi_to_png(raw_ansi_bytes, idx):
    pid = os.getppid()
    ansifile = "{0}-{1}.ans".format(idx, pid)
    pngfile = "{0}-{1}.png".format(idx, pid)
    with open(ansifile, "wb") as fp:
        fp.write(raw_ansi_bytes)
    subprocess.run(["./ansilove", "-d", "-o", pngfile, ansifile])
    with open(pngfile, "rb") as fp:
        png = fp.read()
    os.unlink(ansifile)
    os.unlink(pngfile)
    return png
def ansi_to_png64(raw_ansi_bytes, idx):
    png = ansi_to_png(raw_ansi_bytes, idx)
    return base64.b64encode(png).decode("utf-8")
@app.route(base_path + "/image//.png")
def display_ansi(area, msgno):
    if area not in bases:
        return "RATS", 404
    message = get_message(bases[area], msgno)
    if not message:
        return "RATS", 404
    if not "text" in message:
        return "RATS", 404
    png = ansi_to_png(message["bytes"].replace(b"\r", b"\n"), msgno)
    response = make_response(png)
    response.headers.set("Content-Type", "image/png")
    return response
# 
/")
def display_message(area, msgno):
    if area not in bases:
        return render_template(
            "missing-area.html", base_path=base_path, title="Missing Area"
        )
    # message = jammin.read_message(bases[area], msgno)
    message = get_message(bases[area], msgno)
    if not message:
        return render_template(
            "missing-message.html",
            base_path=base_path,
            area=area,
            title="Missing Message",
        )
    if "text" in message:
        if "\x1b" in message["text"]:
            # Ok, the message contains ANSI CODES -- Convert
            message["png"] = True
            # message["png"] = ansi_to_png64(
            #     message["bytes"].replace(b"\r", b"\n"), msgno
            # )
        else:
            message["text"] = message["text"].replace("\r", "\n")  # 
\n")
    return render_template(
        "message.html",
        message=message,
        area=area,
        msgnumber=msgno,
        base_path=base_path,
        title="Message {0}".format(msgno),
    )