import flask
import datetime
import random
import string
import os

app = flask.Flask(__name__)

code = ""
history = []

@app.route('/musicstatus.html', methods=['GET', 'POST'])
def musicstatus():
    global code, history
    if flask.request.method == 'POST':
        data = flask.request.get_json()
        if code == "":
            return "Verification code not generated"
        if data['verificationcode'] != code:
            return "Verification failed"
        else:
            musicname = data['music']
            time = data['time']
            resetstatus = data['resetstatus']
            history.append((musicname, time, resetstatus))
            return f"{musicname} added to history"
    elif flask.request.method == 'GET':
        html = '<DOCTYPE html>\n<html>\n'
        html += '<head>\n<meta charset="UTF-8">\n<link href="https://fonts.googleapis.com/css2?family=Jetbrains+Mono:wght@400;700&display=swap" rel="stylesheet">\n</head>\n'
        html += '<body style="background-color: #1f1f1f; color: #ffffff; font-family: \'Jetbrains Mono\', monospace;">\n<meta name="viewport" content="width=device-width, initial-scale=1.0">\n'
        html += '<title>Halhadus\' Music Status</title>\n<link rel="icon" type="image/png" href="assets/favicon.png">\n'
        html += '<meta name="description" content="Halhadus\' Music Status">\n<meta property="og:title" content="Halhadus\' Music Status">\n'
        html += '<meta property="og:description" content="Halhadus\' Music Status">\n<meta property="og:image" content="assets/favicon.png">\n'
        html += '<meta property="og:url" content="https://halhadus.rocks/musicstatus.html">\n'
        html += '<h1>Halhadus\' Music Status</h1>\n'
        html += '<a href="https://git.halhadus.rocks/Halhadus/localwrappedmusicstatus-combo-allinonerepo" style="color: #ffffff;">Source Code</a>\n'
        html += '<h3>Hi guys. I am too lazy to add links to song names. To find which song is it, check <a href="musiclist.html" style="color: #ffffff;">this link</a>.</h3>\n'
        html += '<form action="index.html">\n<input type="submit" value="Back to main page" style="background-color: #1f1f1f; color: #ffffff; border: 2px solid #ffffff; border-radius: 5px; padding: 10px 20px; margin: 10px 0px;">\n</form>\n'
        if len(history) > 0:
            if history[-1][2] == "true":
                currentbeforereset = history[-1]
                history = []
                history.append(currentbeforereset)
            html += f'<h2>Currently Playing: {history[-1][0]}</h2>\n'
            html += f'<h2>Last Update Time: {datetime.datetime.fromtimestamp(int(history[-1][1]), datetime.timezone.utc).strftime("%Y-%m-%d %H:%M:%S")} (UTC +0)</h2>\n'
            if os.path.exists("lyrics/" + history[-1][0] + ".lrc"):
                with open("lyrics/" + history[-1][0] + ".lrc", "r") as f:
                    lyrics = f.read().split("\n")
                    lyrics = [lyric.split("]")[1] for lyric in lyrics if "]" in lyric]
                    lyrics = [lyric for lyric in lyrics if not lyric == ""]
                    html += '<h3>Lyrics:</h3>\n'
                    html += '<div style="border: 1px solid #ffffff; padding: 10px; text-align: center;">\n'
                    for lyric in lyrics:
                        html += f'<p>{lyric}</p>\n'
                    html += '</div>\n'
        html += '<table style="width: 100%; border-collapse: collapse;">\n<tr>\n<th style="border: 1px solid #ffffff; padding: 10px;">Music Name</th>\n<th style="border: 1px solid #ffffff; padding: 10px;">Time</th>\n</tr>\n'
        for music in history[::-1]:
            html += '<tr>\n<td style="border: 1px solid #ffffff; padding: 10px;">' + music[0] + '</td>\n<td style="border: 1px solid #ffffff; padding: 10px;">' + datetime.datetime.fromtimestamp(int(music[1]), datetime.timezone.utc).strftime("%Y-%m-%d %H:%M:%S") + '</td>\n</tr>\n'
        html += '</table>\n</body>\n</html>'
        return html

@app.route('/verifykey', methods=['GET', 'POST'])
def verifycert():
    global code
    if flask.request.method == 'POST':
        data = flask.request.get_json()
        key = data['key']
        with open("key.txt", "r") as f:
            if key == f.read():
                code = ''.join(random.choices(string.ascii_uppercase + string.digits, k=64))
                return code
            else:
                return "0"
    elif flask.request.method == 'GET':
        return "GET method not allowed"

@app.route('/<path:path>')
def catch_all(path):
    if path == None:
        return flask.redirect('https://halhadus.rocks')
    if not path == 'musicstatus.html' or not path == 'verifykey':
        return flask.redirect(f'https://halhadus.rocks/{path}')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=int(os.environ.get('PORT')))
