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, 1, 58, 34), 'django.contrib.auth.decorators.login_required', 'login_required', (), '', False, 'from django.contrib.auth.decorators import login_required\n'), ((70, 1, 70, 34), 'django.contrib.auth.decorators.login_required', 'login_required', (), '', False, 'from django.contrib.auth.decorators import login_required\n'), ((77, 1, 77, 34), 'django.contrib.auth.decorators.login_required', 'login_required', (), '', False, 'from django.contrib.auth.decorators import login_required\n'), ((83, 1, 83, 34), 'django.contrib.auth.decorators.login_required', 'login_required', (), '', False, 'from django.contrib.auth.decorators import login_required\n'), ((104, 1, 104, 34), 'django.contrib.auth.decorators.login_required', 'login_required', (), '', False, 'from django.contrib.auth.decorators import login_required\n'), ((15, 11, 15, 55), 'django.shortcuts.render', 'render', ({(15, 18, 15, 25): 'request', (15, 26, 15, 46): '"""memeapp/index.html"""', (15, 47, 15, 54): 'context'}, {}), "(request, 'memeapp/index.html', context)", False, 'from django.shortcuts import render, redirect\n'), ((19, 9, 19, 27), 'django.contrib.auth.forms.UserCreationForm', 'UserCreationForm', ({}, {}), '()', False, 'from django.contrib.auth.forms import UserCreationForm\n'), ((31, 11, 31, 55), 'django.shortcuts.render', 'render', ({(31, 18, 31, 25): 'request', (31, 27, 31, 46): '"""memeapp/auth.html"""', (31, 47, 31, 54): 'context'}, {}), "(request, 'memeapp/auth.html', context)", False, 'from django.shortcuts import render, redirect\n'), ((52, 11, 52, 56), 'django.shortcuts.render', 'render', ({(52, 18, 52, 25): 'request', (52, 27, 52, 46): '"""memeapp/auth.html"""', (52, 48, 52, 55): 'context'}, {}), "(request, 'memeapp/auth.html', context)", False, 'from django.shortcuts import render, redirect\n'), ((55, 4, 55, 19), 'django.contrib.auth.logout', 'logout', ({(55, 11, 55, 18): 'request'}, {}), '(request)', False, 'from django.contrib.auth import authenticate, login, logout\n'), ((56, 11, 56, 28), 'django.shortcuts.redirect', 'redirect', ({(56, 20, 56, 27): '"""index"""'}, {}), "('index')", False, 'from django.shortcuts import render, redirect\n'), ((67, 11, 67, 66), 'django.shortcuts.render', 'render', ({(67, 18, 67, 25): 'request', (67, 27, 67, 56): '"""memeapp/upload_picture.html"""', (67, 58, 67, 65): 'context'}, {}), "(request, 'memeapp/upload_picture.html', context)", False, 'from django.shortcuts import render, redirect\n'), ((75, 11, 75, 89), 'django.shortcuts.render', 'render', ({(75, 18, 75, 25): 'request', (75, 27, 75, 49): '"""memeapp/profile.html"""', (75, 51, 75, 88): "{'profile': images, 'images': profiles}"}, {}), "(request, 'memeapp/profile.html', {'profile': images, 'images': profiles}\n    )", False, 'from django.shortcuts import render, redirect\n'), ((80, 11, 80, 74), 'django.shortcuts.render', 'render', ({(80, 18, 80, 25): 'request', (80, 27, 80, 55): '"""memeapp/image_details.html"""', (80, 57, 80, 73): "{'image': image}"}, {}), "(request, 'memeapp/image_details.html', {'image': image})", False, 'from django.shortcuts import render, redirect\n'), ((122, 11, 122, 58), 'django.shortcuts.render', 'render', ({(122, 18, 122, 25): 'request', (122, 26, 122, 49): '"""memeapp/comments.html"""', (122, 50, 122, 57): 'context'}, {}), "(request, 'memeapp/comments.html', context)", False, 'from django.shortcuts import render, redirect\n'), ((21, 21, 21, 51), 'django.contrib.auth.forms.UserCreationForm', 'UserCreationForm', ({(21, 38, 21, 50): 'request.POST'}, {}), '(request.POST)', False, 'from django.contrib.auth.forms import UserCreationForm\n'), ((37, 16, 37, 33), 'django.shortcuts.redirect', 'redirect', ({(37, 25, 37, 32): '"""index"""'}, {}), "('index')", False, 'from django.shortcuts import render, redirect\n'), ((45, 13, 45, 70), 'django.contrib.auth.authenticate', 'authenticate', (), '', False, 'from django.contrib.auth import authenticate, login, logout\n'), ((95, 15, 95, 28), 'django.shortcuts.redirect', 'redirect', ({(95, 24, 95, 27): '"""/"""'}, {}), "('/')", False, 'from django.shortcuts import render, redirect\n'), ((102, 15, 102, 28), 'django.shortcuts.redirect', 'redirect', ({(102, 24, 102, 27): '"""/"""'}, {}), "('/')", False, 'from django.shortcuts import render, redirect\n'), ((132, 15, 132, 62), 'django.shortcuts.render', 'render', ({(132, 22, 132, 29): 'request', (132, 31, 132, 52): '"""memeapp/search.html"""', (132, 54, 132, 61): 'context'}, {}), "(request, 'memeapp/search.html', context)", False, 'from django.shortcuts import render, redirect\n'), ((134, 8, 134, 68), 'django.contrib.messages.error', 'messages.error', ({(134, 23, 134, 30): 'request', (134, 32, 134, 67): '"""You haven\'t searched for any term"""'}, {}), '(request, "You haven\'t searched for any term")', False, 'from django.contrib import messages\n'), ((136, 15, 136, 75), 'django.shortcuts.render', 'render', ({(136, 22, 136, 29): 'request', (136, 31, 136, 52): '"""memeapp/search.html"""', (136, 54, 136, 74): "{'message': message}"}, {}), "(request, 'memeapp/search.html', {'message': message})", False, 'from django.shortcuts import render, redirect\n'), ((26, 12, 26, 31), 'django.contrib.auth.login', 'login', ({(26, 18, 26, 25): 'request', (26, 26, 26, 30): 'user'}, {}), '(request, user)', False, 'from django.contrib.auth import authenticate, login, logout\n'), ((27, 19, 27, 36), 'django.shortcuts.redirect', 'redirect', ({(27, 28, 27, 35): '"""index"""'}, {}), "('index')", False, 'from django.shortcuts import render, redirect\n'), ((29, 12, 29, 72), 'django.contrib.messages.error', 'messages.error', ({(29, 27, 29, 34): 'request', (29, 36, 29, 71): '"""Error occured during registration"""'}, {}), "(request, 'Error occured during registration')", False, 'from django.contrib import messages\n'), ((42, 17, 42, 52), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', (), '', False, 'from django.contrib.auth.models import User\n'), ((47, 12, 47, 31), 'django.contrib.auth.login', 'login', ({(47, 18, 47, 25): 'request', (47, 26, 47, 30): 'user'}, {}), '(request, user)', False, 'from django.contrib.auth import authenticate, login, logout\n'), ((48, 19, 48, 36), 'django.shortcuts.redirect', 'redirect', ({(48, 28, 48, 35): '"""index"""'}, {}), "('index')", False, 'from django.shortcuts import render, redirect\n'), ((50, 12, 50, 74), 'django.contrib.messages.error', 'messages.error', ({(50, 27, 50, 34): 'request', (50, 36, 50, 73): '"""Username OR Password does not exist"""'}, {}), "(request, 'Username OR Password does not exist')", False, 'from django.contrib import messages\n'), ((65, 19, 65, 36), 'django.shortcuts.redirect', 'redirect', ({(65, 28, 65, 35): '"""index"""'}, {}), "('index')", False, 'from django.shortcuts import render, redirect\n'), ((116, 19, 116, 36), 'django.shortcuts.redirect', 'redirect', ({(116, 28, 116, 35): '"""index"""'}, {}), "('index')", False, 'from django.shortcuts import render, redirect\n'), ((44, 12, 44, 58), 'django.contrib.messages.error', 'messages.error', ({(44, 27, 44, 34): 'request', (44, 36, 44, 57): '"""User does not exist"""'}, {}), "(request, 'User does not exist')", False, 'from django.contrib import messages\n'), ((112, 93, 112, 107), 'datetime.datetime.now', 'datetime.now', ({}, {}), '()', False, 'from datetime import datetime\n')]