from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.contrib.auth.models import User
from .models import UserProfile, MessageModel
from .forms import UserProfileForm, UserProfileFormEdit, RegistrationForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login
from accounts.forms import RegistrationForm

""" REGISTER API =================================================================================== """
@login_required(login_url='/login')
def register(request):
    template_name = 'registration/register.html'

    """ CHECK IF USER IS AUTHORIZED """
    if request.user.profile_set.role != "SUPERADMIN":
        messages.error(request, 'USER IS NOT ALLOWED!!!')
        return redirect('/')

    
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        form_profile = UserProfileForm(request.POST)
        if form.is_valid() and form_profile.is_valid():
            new_user = form.save()
            new_profile = form_profile.save(commit=False)
            new_profile.user = new_user
            new_profile.save()
            #user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'])
            #login(request, user)
            #return redirect('/accounts/create-profile/')
            messages.success(request, 'LOGIN NEW USER TO COMPLETE REGISTRATION!!!')
            return redirect('/logout')
        #form = UserCreationForm()
        return render(request, template_name, {'form':form, 'form_profile':form_profile})

    else:
        form = RegistrationForm()
        form_profile = UserProfileForm()
    return render(request, template_name, {'form':form, 'form_profile':form_profile})





@login_required(login_url='/login')
def create_profile(request):
    profile = UserProfile.objects.filter(user_id=request.user).first()
    if profile:
        messages.error(request, 'PROFILE ASSOCIATED WITH USER FOUND!!!')
        return redirect(f'/profile/{profile.id}')

    template_name = 'create-profile.html'

    if request.method == 'POST':
        form = UserProfileForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.user_id = request.user
            obj.created_by = request.user.username
            obj.save()

            usr = User.objects.get(username=request.user.username)
            if not usr.email:
                usr.email = request.POST.get('email')
                usr.save()
                
            messages.success(request, 'PROFILE UPDATED SUCCESSFULLY')
            return redirect('/')
        messages.error(request, 'PROFILE UPDATE FAILED')
        form = UserProfileForm()
        return render(request, template_name, {'form':form})
    else:
        form = UserProfileForm()
        return render(request, template_name, {'form':form})


""" GET USER PROFILE ======================================================================================================= """
@login_required(login_url='/login')
def profile(request, pk):
    profile = UserProfile.objects.filter(user_id=request.user).first()
    #profilepk = UserProfile.objects.get(pk=pk)

    if not profile:
        messages.error(request, 'PROFILE NOT FOUND!!!')
        return redirect('/')

    if profile.id != pk:
        messages.error(request, 'PROFILE MISMATCH FOUND!!!')
        return redirect('/')

    template_name = 'profile.html'

    if request.method == 'POST':
        profileID = request.POST.get('profileID')
        if int(profileID) != pk:
            return redirect('/')

        form = UserProfileFormEdit(request.POST, instance=profile)
        if form.is_valid():
            form.save()
            
            messages.success(request, 'PROFILE UPDATED SUCCESSFULLY')
            return redirect(f'/profile/{pk}')
        messages.error(request, 'PROFILE UPDATE FAILED')
        form = UserProfileFormEdit(instance=profile)
        return render(request, template_name, {'form':form, 'profile':profile})
    else:
        form = UserProfileFormEdit(instance=profile)
        return render(request, template_name, {'form':form, 'profile':profile})


""" CHANGE PASSWORD API ======================================================================== """
@login_required(login_url='/login')
def change_password(request, profile, pk):
    if request.method == 'POST':
        new_password1 = request.POST.get('new_password1')
        new_password2 = request.POST.get('new_password2')
        profileID = request.POST.get('profileID')

        if new_password1 != new_password2:
            messages.error(request, 'INCORRECT PASSWORDS!!!')
            return redirect(f'/profile/{pk}')

        if int(pk) != int(profileID):
            messages.error(request, 'MISMATCH PROFILE!!!')
            return redirect('/')

        #profilepk = UserProfile.objects.get(pk=pk)
        profile = UserProfile.objects.filter(user_id=request.user).first()

        if profile.id != pk:
            messages.error(request, 'PROFILE MISMATCH!!!')
            return redirect('/')

        usr = User.objects.get(username=request.user.username)
        if usr:
            usr.set_password(new_password1)
            usr.save()

            messages.success(request, 'PASSWORD UPDATE SUCCESSFUL')
            return redirect(f'/profile/{pk}')
        messages.error(request, 'USER NOT FOUND!!!')
        return redirect('/')
    else:
        messages.error(request, 'NOT ALLOWED!!!')
        return redirect('/')


""" MESSAGE CHAT =================================================== """
from rest_framework.parsers import JSONParser
from django.http.response import JsonResponse
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
@login_required(login_url='/login')
def create_message(request):
    if request.method == 'GET':
        messages.error(request, 'Method not allowed!!!')
        return JsonResponse({"error":"Method not allowed!!!"}, safe=False)
    
    elif request.method == 'POST':
        data = JSONParser().parse(request)
        
        sender = data['sender']
        message = data['message']
        r = data['receiver'].split(' ')

        if len(r) != 2:
            messages.error(request, 'Receipent not Found!!!')
            return JsonResponse({"error":"Name error, Receipent not Found!!!"}, safe=False)

        receiver = User.objects.filter(first_name=r[0], last_name=r[1]).first()
        if not receiver:
            messages.error(request, 'Receipent not Found!!!')
            return JsonResponse({"error":"Receipent not Found!!!"}, safe=False)

        if receiver == request.user:
            messages.error(request, 'You cannot send message to Yourself!!!')
            return JsonResponse({"error":"Duplicate user!!!"}, safe=False)
        
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')

        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        
        new_mssg = MessageModel(sender=sender, receiver = receiver, message=message, created_by=request.user.username, user_ip=ip)
        new_mssg.save()
        messages.success(request, 'Message sent')
        return JsonResponse({"message":f"Message sent to {data['receiver']}"}, safe=False)


""" DISPLAY USER MESSAGES """
@login_required(login_url='/login')
def message(request):
    template_name = 'message.html'
    mssg = list(MessageModel.objects.filter(receiver=request.user).order_by('is_read', '-datetime_created').values())
    return render(request, template_name, {'mssg':mssg})


""" READ MESSAGES ========================================================================"""
@login_required(login_url='/login')
def message_read(request, pk):
    mssg = get_object_or_404(MessageModel, pk=pk)
    mssg.is_read = True
    mssg.save()
    return redirect('/message')



""" GET USER MESSAGES ========================================================================"""
@login_required(login_url='/login')
def get_user_message_api(request):
    mssg = list(MessageModel.objects.filter(receiver=request.user, is_read=False).values())
    return JsonResponse({'message':mssg}, safe=False)
    

""" GET USER API =============================================================================== """

def get_current_user_api(request):
    #current_user = User.objects.filter(id= request.user.id).first()
    current_user = request.user

        
    if not current_user:
        #return JsonResponse({'status':'failed'}, safe=False)
        return JsonResponse({'status':'success', 'fname':'current_user_first_name', 'id':'current_user_id', 'role':'role'}, safe=False)

    else:
        profile = UserProfile.objects.filter(user=current_user).first()
        if profile:
            role = profile.role
        else:
            role = ''

        return JsonResponse({'status':'success', 'fname':current_user.first_name, 'id':current_user.id, 'role':role}, safe=False)


