from flask import render_template, request
from PIL import Image
# import database, re, bcrypt, secrets, time
import secrets, time, os, database
from auth import get_session
from app import app


@app.route("/entry/<pid>/interactions/<mode>", methods=['GET'])
def interactions(pid, mode):
    # session = get_session(request)

    # empty = (mode!='left' and mode!='right')
    # selected = 'none'

    # if session and not empty:
    #     uid = session[0]
    #     previous = database.fetch("SELECT mode FROM vote WHERE uid=? AND pid=?", [uid, pid])
    #     if len(previous) == 0:
    #         selected=mode
    #         database.execute("INSERT INTO vote (uid, pid, mode) VALUES (?,?,?)", [uid, pid, mode])
    #     else:

    #         previous = previous[0][0]
    #         previous = 'none'

    #     if previous < 1:
    #     elif previous[0][0]==mode:
    #         database.execute("DELETE FROM vote WHERE uid=? AND pid=?", [uid, pid])
    #     else:
    #         database.execute("UPDATE vote SET mode=? WHERE uid=? AND pid=?", [mode, uid, pid])

    # left = database.fetch("SELECT COUNT(id) FROM vote WHERE pid=? and mode='left';", [pid])[0][0]
    # right = database.fetch("SELECT COUNT(id) FROM vote WHERE pid=? and mode='right';", [pid])[0][0]

    # return render_template("entry/interactions.html", pid=pid, stats=f"{left} {right} {mode}")
    return "--"

@app.route("/entry/feed/<page>", methods=['GET'])
def feed(page):
    page = int(page, 0)
    page = max(0,page)
    page = min(100,page)

    count = 20
    offset = page*count

    posts = database.fetch("SELECT * FROM entry ORDER BY created_at DESC LIMIT ? OFFSET ?", [count, offset])

    if len(posts) <= 0:
        return """<div id="infinite-scroll-indicator">
        <h2>YOU REACHED THE END!</h2>
        </div>"""

    posts_with_usernames = []
    for post in posts:
        username = database.fetch("SELECT username FROM user WHERE uid = ?", [post[2]])
        posts_with_usernames.append(post + username[0])

    return render_template("entry/feed.html", posts=posts_with_usernames, page=page)

@app.route("/entry/create", methods=['GET', 'POST'])
def newentry():
    session = get_session(request)

    if not session:
        return "Melde dich an, um einen Beitrag zu erstellen!"

    uid = session[0]

    if request.method == 'GET':
        return render_template('entry/create.html')

    content = str(request.form["content"])
    content = content.strip()
    content = content[:1000]

    fileattached = False
    if 'file' in request.files:
        file = request.files['file']
        fileattached=True

    if fileattached:
        fileattached = _storeimage(file)

    if not fileattached and content == '':
        return render_template('entry/create.html', responses=["Leerer Beitrag!"])

    if not fileattached:
        fileattached = "none"

    pid = secrets.randbelow(999999999999)
    now = int(time.time())
    database.execute("""INSERT INTO entry
        (pid, uid, created_at, content, filepath)
        VALUES (?, ?, ?, ?, ?)""",
        (pid, uid, now, content, fileattached))

    return render_template('entry/create.html', responses=[content, str(fileattached)])

def _storeimage(file):
    maxsize = 1024
    tmpfile = secrets.randbelow(999999)
    tmppath = f"tmp/{tmpfile}"

    import resizegif

    try:
        file.save(tmppath)

        i = Image.open(tmppath)
        if i.format == 'GIF':
            filetype = 'gif'
        else:
            i = i.convert("RGB")
            filetype = 'jpg'

        newpath = f"static/media/{int(time.time())}-{tmpfile}.{filetype}"

        (width, height) = i.size;
        aspect = width/height

        if width < maxsize and height < maxsize:
            if filetype == 'gif':
                resizegif.resize_gif(i, newpath, (width, height))
            else:
                i.save(newpath)

            os.remove(tmppath)
            return newpath 

        if width > height:
            width = maxsize
            height = maxsize/aspect
        else:
            height = maxsize
            width = aspect*maxsize

        if filetype == 'gif':
            resizegif.resize_gif(i, newpath, (width, height))
        else:
            i.thumbnail((width, height), Image.Resampling.LANCZOS)
            i.save(newpath)

        os.remove(tmppath)
        return newpath
    except Exception as e:
        print(e)
        os.remove(tmppath)
        return False
