from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from json import loads, dumps
from math import floor
import requests
from .forms import ServerAddressForm, BackendFilepathForm
import logging

# Create your views here.

# Debug and defaults.
defaults = {
    'listen_address': 'http://localhost:8000/',
    'backend_filepath': '',
    'backend_filepath_updated': False,
}
# default_address = 'http://localhost:8000/'
# logging.basicConfig(encoding='utf-8', level=logging.DEBUG)


def session_key(session, key):
    if key not in session.keys():
        session[key] = defaults[key]

    # TODO: consider serializing user sessions for debugging in the future.
    logging.info(
        f'Session {key} set to: {session[key]}')
    return session[key]

    is_hidden = True


def index(request):
    request_data = None

    listen_address = session_key(request.session, 'listen_address')
    backend_filepath = session_key(request.session, 'backend_filepath')

    try:
        request_data = requests.get(
            f'{server_address}spoiler', timeout=5, verify=True).text
    except:
        with open('empty_spoiler.json', 'r') as t:
            try:
                tracker_output = loads(t.read())
                is_hidden = False

            except:
                return
    try:
        tracker_output = loads(request_data)
    except:
        with open('empty_spoiler.json', 'r') as t:
            try:
                tracker_output = loads(t.read())
                is_hidden = False
            except:
                return
    with open('tracker/static/tracker/data/holy_cross_codes.json', 'r') as t:
        try:
            temp_codes = loads(t.read())
            cross_codes = {x: {k: l.replace('U', '⬆️').replace('D', '⬇️').replace('L', '⬅️').replace(
                'R', '➡️').strip() for k, l in temp_codes[x].items()} for x in temp_codes.keys()}
        except:
            return
    tracker_debug = tracker_output['Debug']
    tracker_totals = tracker_output['Totals']
    tracker_current_scene = tracker_output['Current']['Scene']
    tracker_current_scene_data = tracker_output['Scenes'][tracker_current_scene]
    tracker_scenes = tracker_output['Scenes']
    entered_codes = tracker_output['Codes']
    try:
        tracker_codes = cross_codes
        for scene in entered_codes:
            for k, v in cross_codes[scene].items():
                tracker_codes[scene][k] = (
                    v, entered_codes[scene][k])
    except Exception as e:
        current_cross_codes = {}
        # print(e)
    template = loader.get_template('tracker/index.html')
    server_address_form = ServerAddressForm()
    server_address_form.fields['server_address_form'].initial = listen_address
    backend_filepath_form = BackendFilepathForm()
    backend_filepath_form.fields['backend_filepath_form'].initial = backend_filepath
    context = {
        'backend_filepath': backend_filepath,
        'server_address': listen_address,
        'is_hidden': is_hidden,
        'debug': tracker_debug,
        'default_codes': cross_codes['Default'],
        'tracked_codes': tracker_codes,
        'totals': tracker_totals,
        'scenes': tracker_scenes,
        'current_scene': {
            'title': tracker_current_scene,
            'data': tracker_current_scene_data
        },
        'server_address_form': server_address_form,
        'backend_filepath_form': backend_filepath_form
    }
    return HttpResponse(template.render(context, request))


def get_address(request):
    if request.method == 'GET':
        session_key(request.session, 'backend_filepath_updated')
        return HttpResponse(dumps({'listen_address': request.session['listen_address'], 'backend_filepath_updated': request.session['backend_filepath_updated']}), content_type="application/json")
    else:
        return render(request, 'tracker/index.html')


def set_address(request):
    if request.method == 'POST':
        form = ServerAddressForm(request.POST)
        if form.is_valid():
            request.session['listen_address'] = form.cleaned_data['server_address_form']
            return HttpResponseRedirect('/')
    else:
        form = ServerAddressForm()
    return render(request, 'tracker/index.html', {'server_address_form': form})


def set_settings(request):
    if request.method == 'POST':
        form = BackendFilepathForm(request.POST)
        if form.is_valid():
            request.session['backend_filepath'] = form.cleaned_data['backend_filepath_form']
            request.session['backend_filepath_updated'] = True
            return HttpResponseRedirect('/')
    else:
        form = BackendFilepathForm()
    return render(request, 'tracker/index.html', {'backend_filepath_form': form})


def get_settings(request):
    if request.method == 'GET':
        request.session['backend_filepath_updated'] = False
        return HttpResponse(dumps(request.session['backend_filepath']), content_type="application/json")
    else:
        return render(request, 'tracker/index.html')
