#!/usr/bin/python3
import zlib
from main import *
from adventurers import *
from flask import Flask, render_template, redirect, request, make_response
from flask_session import Session

app = Flask(__name__)

# Configure session
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)


@app.route('/')
def index():
    tab = request.args.get("tab", default="what", type=str)
    return render_template("index.html", tab=tab)

@app.route('/party', methods = ["GET","POST"])
def party():
    stored_adv_party = []
    stored_count = None
    stored_level = None
    if request.method == "GET":
        count = request.args.get("count", default=4, type=int)
        level = request.args.get("level", default=1, type=int)
        cache = request.args.get("cache", default='true', type=str)
        adv_party = returnParty(count, level) 
        # check for cookies present
        if request.cookies:
            stored_count = len(request.cookies)
            #print(request.cookies)
            for c in request.cookies:
                if c.startswith('adv'):
                    cookie_encoded = request.cookies[c]
                    cookie_compressed = base64.urlsafe_b64decode(cookie_encoded)
                    character_dict = json.loads(zlib.decompress(cookie_compressed).decode())
                    new_char = createCharacterWithDict(character_dict)
                    stored_level = new_char.level
                    stored_adv_party.append(new_char)
            # if request arguments match the adventure party count & level stored in the cookies, just use the cookies
            if cache == 'true':
                if level != stored_level:
                    for adv in stored_adv_party:
                        adv.set_level(level)
                        print(adv.level)
                if count == stored_count:
                    adv_party.set_party(stored_adv_party, count, level)
                if count > stored_count:
                    extension = count - stored_count
                    more_party_members = returnParty(extension,level).adventurers
                    extended_party = stored_adv_party + more_party_members
                    adv_party.set_party(extended_party, count, level)
                if count < stored_count:
                    reduction = count - stored_count
                    reduced_party = stored_adv_party[:reduction]
                    adv_party.set_party(reduced_party, count, level)


        # generate page
        response = make_response(render_template("party_sheet.html", adv_party=adv_party, count=count, level=level, cache=cache))
        # make a cookie for each character
        # this took a while to figure out, json was too large, b64 encoded json was too large, but it turns out you can compress json as a cookie
        for character in adv_party.adventurers:
            cookie_string = character.identifier
            char_json = json.dumps(character.get_json())
            compressed = zlib.compress(char_json.encode())
            cookie_data = base64.urlsafe_b64encode(compressed).decode()
            response.set_cookie(cookie_string, cookie_data)
        return response

@app.route('/character', methods = ["GET","POST"])
def character():
    if request.method == "GET":
        print('in get')
        c_id = str(request.args.get("id", default="adv-1", type=str))
        if request.cookies:
            cookie_encoded = request.cookies[c_id]
            cookie_compressed = base64.urlsafe_b64decode(cookie_encoded)
            character_dict = json.loads(zlib.decompress(cookie_compressed).decode())
            new_char = createCharacterWithDict(character_dict)
        else:
            print('in else')
            new_player = Adventurer(c_id, 1)
            selected_class = ClassSelector(new_player).selection()
            new_char = selected_class(new_player.identifier, new_player.level, new_player.get_attributes())
    return render_template("character.html", character=new_char)
