from django.shortcuts import render,redirect
from django.contrib.auth.models import User
from django.contrib import messages
from .forms import PictureUploadForm,CommentForm
from .models import Image,Profile,Likes,Comments
from django.contrib.auth.decorators import login_required
from django.contrib .auth import authenticate,login,logout
from django.contrib.auth.forms import UserCreationForm
from datetime import datetime


def index(request):
    images=Image.objects.all()
    context={'images':images}
    return render(request,'memeapp/index.html',context)


def registerPage(request):
    form=UserCreationForm()
    if request.method == "POST":
        form_results=UserCreationForm(request.POST)
        if form_results.is_valid():
            user =form_results.save(commit=False)
            user.username=user.username.lower()
            user.save()
            login(request,user)
            return redirect('index')
        else:
            messages.error(request, 'Error occured during registration')
    context = {'reg_form':form}
    return render(request, 'memeapp/auth.html',context)


def loginPage(request):
    page='login'
    if request.user.is_authenticated:
        return  redirect('index')
    if request.method == "POST":
        username=request.POST.get('username').lower()
        password=request.POST.get('password')
        try:
            user=User.objects.get(username=username)
        except:
            messages.error(request, 'User does not exist')
        user=authenticate(request,username=username,password=password)
        if user is not None:
            login(request,user)
            return redirect('index')
        else:
            messages.error(request, 'Username OR Password does not exist')
    context={'page':page}
    return render(request, 'memeapp/auth.html', context)

def logoutUser(request):
    logout(request)
    return redirect('index')

@login_required(login_url='login')
def uploadPicture(request):
    form = PictureUploadForm()
    if request.method == "POST":
        form_results = PictureUploadForm(request.POST,request.FILES)
        if form_results.is_valid():
            form_results.save()
            return redirect('index')
    context = {"form": form}
    return render(request, 'memeapp/upload_picture.html', context)


@login_required(login_url='login')
def my_images(request):
    current_user = request.user
    images = Profile.objects.filter(user_id=current_user.id).first()
    profiles = Image.objects.filter(user_id=current_user.id)
    return render(request, 'memeapp/profile.html', {"profile": images,"images":profiles})

@login_required(login_url='login')
def each_image(request, id):
    image = Image.objects.get(id=id)
    return render(request, 'memeapp/image_details.html', {'image': image})


@login_required(login_url='login')
def like_picture(request, id):
    likes = Likes.objects.filter(image_id=id).first()
    if Likes.objects.filter(image_id=id, user_id=request.user.id).exists():
        likes.delete()
        image = Image.objects.get(id=id)
        if image.likes_number == 0:
            image.likes_number = 0
            image.save()
        else:
            image.likes_number -= 1
            image.save()
        return redirect('/')
    else:
        likes = Likes(image_id=id, user_id=request.user.id)
        likes.save()
        image = Image.objects.get(id=id)
        image.likes_number = image.likes_number + 1
        image.save()
        return redirect('/')

@login_required(login_url='login')
def comment(request,pk):
    profile = Image.objects.get(pk=pk)
    form_results = CommentForm(request.POST,instance=profile)
    if request.method == "POST":
        if form_results.is_valid():
            user = request.user
            comment= form_results.cleaned_data['comment']
            comment_content = Comments(user=user, image=profile, comment=comment, created_on=datetime.now())
            comment_content.save()
            profile.comments_number = profile.comments_number + 1
            profile.save()
            return redirect('index')
        else:
            print('form is invalid')
    else:
        form_results = CommentForm
    context = {'form':form_results,'image':profile}
    return render(request,'memeapp/comments.html',context)


def search(request):
    title = "Search"
    if 'search_query' in request.GET and request.GET["search_query"]:
        search_term = request.GET.get("search_query").lower()
        searched_results = Image.search_image(search_term)
        message = f"{search_term}"
        context = {'message': message, 'results': searched_results, 'title': title}
        return render(request, 'memeapp/search.html', context)
    else:
        messages.error(request, "You haven't searched for any term")
        message = "You haven't searched for any term"
        return render(request, 'memeapp/search.html', {"message": message})


[(58, 'django.contrib.auth.decorators.login_required', 'login_required', False, 'from django.contrib.auth.decorators import login_required\n'), (70, 'django.contrib.auth.decorators.login_required', 'login_required', False, 'from django.contrib.auth.decorators import login_required\n'), (77, 'django.contrib.auth.decorators.login_required', 'login_required', False, 'from django.contrib.auth.decorators import login_required\n'), (83, 'django.contrib.auth.decorators.login_required', 'login_required', False, 'from django.contrib.auth.decorators import login_required\n'), (104, 'django.contrib.auth.decorators.login_required', 'login_required', False, 'from django.contrib.auth.decorators import login_required\n'), (15, 'django.shortcuts.render', 'render', False, 'from django.shortcuts import render, redirect\n'), (19, 'django.contrib.auth.forms.UserCreationForm', 'UserCreationForm', False, 'from django.contrib.auth.forms import UserCreationForm\n'), (31, 'django.shortcuts.render', 'render', False, 'from django.shortcuts import render, redirect\n'), (52, 'django.shortcuts.render', 'render', False, 'from django.shortcuts import render, redirect\n'), (55, 'django.contrib.auth.logout', 'logout', False, 'from django.contrib.auth import authenticate, login, logout\n'), (56, 'django.shortcuts.redirect', 'redirect', False, 'from django.shortcuts import render, redirect\n'), (67, 'django.shortcuts.render', 'render', False, 'from django.shortcuts import render, redirect\n'), (75, 'django.shortcuts.render', 'render', False, 'from django.shortcuts import render, redirect\n'), (80, 'django.shortcuts.render', 'render', False, 'from django.shortcuts import render, redirect\n'), (122, 'django.shortcuts.render', 'render', False, 'from django.shortcuts import render, redirect\n'), (21, 'django.contrib.auth.forms.UserCreationForm', 'UserCreationForm', False, 'from django.contrib.auth.forms import UserCreationForm\n'), (37, 'django.shortcuts.redirect', 'redirect', False, 'from django.shortcuts import render, redirect\n'), (45, 'django.contrib.auth.authenticate', 'authenticate', False, 'from django.contrib.auth import authenticate, login, logout\n'), (95, 'django.shortcuts.redirect', 'redirect', False, 'from django.shortcuts import render, redirect\n'), (102, 'django.shortcuts.redirect', 'redirect', False, 'from django.shortcuts import render, redirect\n'), (132, 'django.shortcuts.render', 'render', False, 'from django.shortcuts import render, redirect\n'), (134, 'django.contrib.messages.error', 'messages.error', False, 'from django.contrib import messages\n'), (136, 'django.shortcuts.render', 'render', False, 'from django.shortcuts import render, redirect\n'), (26, 'django.contrib.auth.login', 'login', False, 'from django.contrib.auth import authenticate, login, logout\n'), (27, 'django.shortcuts.redirect', 'redirect', False, 'from django.shortcuts import render, redirect\n'), (29, 'django.contrib.messages.error', 'messages.error', False, 'from django.contrib import messages\n'), (42, 'django.contrib.auth.models.User.objects.get', 'User.objects.get', False, 'from django.contrib.auth.models import User\n'), (47, 'django.contrib.auth.login', 'login', False, 'from django.contrib.auth import authenticate, login, logout\n'), (48, 'django.shortcuts.redirect', 'redirect', False, 'from django.shortcuts import render, redirect\n'), (50, 'django.contrib.messages.error', 'messages.error', False, 'from django.contrib import messages\n'), (65, 'django.shortcuts.redirect', 'redirect', False, 'from django.shortcuts import render, redirect\n'), (116, 'django.shortcuts.redirect', 'redirect', False, 'from django.shortcuts import render, redirect\n'), (44, 'django.contrib.messages.error', 'messages.error', False, 'from django.contrib import messages\n'), (112, 'datetime.datetime.now', 'datetime.now', False, 'from datetime import datetime\n')]