from django.shortcuts import render, redirect
from django.http import JsonResponse, HttpResponse, HttpResponseRedirect
from django.utils.http import url_has_allowed_host_and_scheme
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import reverse
import os
import json

def login_page(request):
    if request.method == 'POST':
        redirect_to = request.POST.get('next', "/")
        redirect_to = (redirect_to
                       if url_has_allowed_host_and_scheme(redirect_to, request.get_host())
                       else "/endpointnonvalido")
        form = AuthenticationForm(request, request.POST)
        if form.is_valid():
            user = form.get_user()
            login(request, user)
            return redirect(redirect_to)
        else:
            print(form.errors.as_data())
            return render(request, "login.html", {'form': form})
    else:
        if request.user.is_authenticated:
            return redirect("/")
        form = AuthenticationForm()
        for x in form.fields:
            form.fields[x].widget.attrs.update({"class": "form-control"})
        redirect_to = request.GET.get('next', '/')
        redirect_to = (redirect_to
                       if url_has_allowed_host_and_scheme(redirect_to, request.get_host())
                       else '/')
        return render(request, "login.html", {'form': form, 'next': redirect_to})


def logout_page(request):
    logout(request)
    return redirect("/")

def is_authenticated(request):
    if request.user.is_authenticated:
        out = {'user': request.user.username}
    else:
        out = {'user': None}
    return JsonResponse(out)

def index(request):
    return HttpResponseRedirect("/admin/")

def auto_config_frontend(request):
    auto_config_frontend = {
        #'api_url': reverse('sangue_app:api-root'),
        #'mqtt_url': "/mqtt/",
        'nome_deployment': os.getenv('DEPLOY_NAME',''),
        'context': os.getenv('CONTEXT','')
    }
    return HttpResponse("let auto_config_frontend = " + json.dumps(auto_config_frontend) + ";", content_type="text/javascript")
