from django.shortcuts import render,get_object_or_404,redirect
from django.contrib.auth import authenticate, login , logout
from django.views.generic import TemplateView
from django.contrib.auth.models import User
from django.contrib import messages
from django.http import *
import random
from doucoder import settings

from django.contrib.sites.shortcuts import get_current_site
from django.template.loader import render_to_string
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode,urlsafe_base64_decode
from django.core.mail import EmailMessage, send_mail
from .token import account_activation_token

# Create your views here.

def conf(request):
    return render (request,'pages/temp_email.html')



class Profile (TemplateView):

    template_name="auth/profile.html"

    def get(self, request, *args, **kwargs):

        usernameSearch = self.kwargs['username']
        userAuth = request.user.username
        is_user_auth=False
        userObjet = get_object_or_404(User,username=usernameSearch)

        if usernameSearch == request.user.username:
            is_user_auth = True


        return render(request,self.template_name,{'user':userObjet,'is_auth':is_user_auth})

class Inscription(TemplateView):
    template_name='pages/registre.html'  

    def get(self, request, *args, **kwargs):
        if request.user.is_authenticated:
            return redirect('/')
        return render(request,self.template_name)

    def post(self,request,**arg):
    
        password = request.POST['password']
        nom = request.POST['nom']
        email = request.POST['email']
        username= email.split('@')[0] + str(random.randint(0,99))

        name = nom.split(" ")
        firstname = ""
        lastname = ""

        print(name)

        try:
            if len(name) == 1 :
                firstname = name[0]

            elif len(name) == 2:
                firstname = name[0] 
                lastname = name[1] 
            else:
                firstname = nom
        except:
            
            print("test")
        


        userExist = User.objects.filter(email__exact=email)
        
        if len(userExist)!= 0:
            messages.error(request,"this mail is already exist")
            
            return render(request,self.template_name) 

        if password == "":
            messages.error(request,"passwords are not the same")
            
            return render(request,self.template_name) 

        #print(username+'  '+password+' '+nom+' '+email)

        user = User()
        user = User.objects.create_user(password=password,email=email,username=username, first_name = firstname, last_name = lastname)
        user.is_activate = False
        user.save()

        current_site = get_current_site(request)
        mail_subject = 'Activate your blog account.'
        message = render_to_string('pages/temp_email.html', {
            'user': user,
            'domain': current_site.domain,
            'uid':urlsafe_base64_encode(force_bytes(user.pk)),
            'token':account_activation_token.make_token(user),
        })

        to_email = email
        
        email_from = settings.EMAIL_HOST_USER

        user = User.objects.filter(email__exact=email)

        send_mail( mail_subject, message, email_from, [to_email] )

        
        if user is not None :
            
            return render(request,'pages/confirmationmail.html',{"to_email":to_email}) 

        return render(request,self.template_name)


class Authentification(TemplateView):
    template_name='pages/login.html'

    def get(self, request) :
        if request.user.is_authenticated:
            return redirect('/')
        return render(request,self.template_name)

    def post(self,request, **arg):

        usernameU = request.POST['email']
        passwordU = request.POST['password']

        
        userS = User.objects.get(email__exact=usernameU)
        
        user = authenticate(username=userS.username, password=passwordU)
        
        if user is not None and user.is_active:

            login(request,user)

            return redirect('/')
        else:
            messages.error(request,"identifications or password failed ")
        
        return redirect('/login')



class Logout (TemplateView):
    template_name='index.html'

    def get(self, request, *args, **kwargs):
        # if not request.user.is_authenticated:
        #     return redirect('/')
        logout(request)
    
        return redirect('/')






def activate(request, uidb64, token):
    try:
        uid = force_text(urlsafe_base64_decode(uidb64))

        user = User.objects.get(pk=uid)
    except(TypeError, ValueError, OverflowError, User.DoesNotExist):
        user = None
    if user is not None and account_activation_token.check_token(user,token):
        user.is_active = True
        user.save()
        login(request, user)
        return redirect('home')
        
    else:
        return HttpResponse('Activation link is invalid!')