from django.contrib import messages
from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponse, HttpResponseRedirect

#from django.contrib.auth.models import User
from .models import User
from .forms import UserForm #todo

# Create your views here.

#user creation view
def user_create(request):
    form = UserForm(request.POST or None)
    if form.is_valid():
        instance = form.save(commit=False)
        print(form.cleaned_data.get("Name"))
        instance.save()
        messages.success(request, "Successfully created user!")
        return redirect("user:user_list")
    context = {
        'form': form,
        'buttontext': 'Create User',
    }
    return render(request, 'usercreate.html', {'context': context, 'form': form})

#user details
def user_details(request, id=None):
    instance = get_object_or_404(User, id=id)
    context = {
        'instance': instance,
    }
    return render(request, 'userdetails.html', context)

#user list, obsolete
def user_list(request):
    user_list = User.objects.all()
    context = {
        "user_list": user_list
    }
    return render(request, "userlist.html", context)

#edit user info
def user_edit(request, id=None):
    instance = get_object_or_404(User, id=id)
    form = UserForm(request.POST or None, instance=instance)
    if form.is_valid():
        instance = form.save(commit=False)
        print(form.cleaned_data.get("Name"))
        instance.save()
        messages.success(request, "Updated successfully.")
        return HttpResponseRedirect(instance.get_absolute_url())
    context = {
        'form': form,
        'buttontext': 'Update User',
    }
    return render(request, 'useredit.html', context)

def user_pagefailure(request):
    return HttpResponse("<b1>Invalid page.</b1>")

def user_invite(request, id=None):
    # Make sure a user is logged in
    if not request.user.is_authenticated():
        return redirect('landing:index')
    # Make sure they have a valid invitation
    if(id == None):
        return redirect('dashboard:index')

    # Find the datablock for that user
    instance = DataBlock.objects.filter(id=id)
    # If the datablock is already used, fail
    if(instance.user != None):
        return redirect('dashboard:index')

    # Otherwise, complete the datablock
    instance.user = request.user
