from django.dispatch.dispatcher import receiver
from django.shortcuts import get_object_or_404, redirect, render
from django.contrib.auth.decorators import login_required
from django.http.response import HttpResponse
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, logout as auth_logout, login as auth_login
from django.contrib import messages
from django.db.models import Count
from django.template.loader import render_to_string
from django.http import HttpResponseRedirect, JsonResponse


from twitter.models import Tweet, Follow, Notification, Comment
from twitter.myDecor import check_if_user_logged
from twitter.forms import SignUpForm

# Create your views here.
@check_if_user_logged
def index(request):
    return render(request, 'index.html')

@check_if_user_logged
def login(request):
    if request.method == 'POST':
        if 'login' in request.POST:
            mail = request.POST['email']
            pwd = request.POST['password']
            user = authenticate(request, username=mail, password=pwd)
            if user is not None:
                auth_login(request, user)
                return redirect('home')
            else:
                messages.error(request, 'Invalid credentials')
                return render(request, 'login.html') 
        elif 'cancel' in request.POST:
            return redirect('index')
    else:
        return render(request, 'login.html')

def logout(reqeuest):
    auth_logout(reqeuest)
    return redirect('index')

@check_if_user_logged
def register(request):
    if request.method == 'POST':
        if 'cancel' in request.POST:
            return redirect('index')
        elif 'register' in request.POST:
            form = SignUpForm(request.POST)
            if form.is_valid():
                user = form.save()
                email = form.cleaned_data.get('email')
                raw_password = form.cleaned_data.get('password')
                user.set_password(raw_password)
                user.save()
                user = authenticate(request, username=email, password = raw_password)
                auth_login(request, user)
                return redirect('home')
            else:
                form = SignUpForm()
                messages.error(request, 'Invalid form fill')
                return render(request, 'register.html', {'form':form})            
    else:
        form = SignUpForm()
        return render(request, 'register.html', {'form':form})

@login_required(redirect_field_name=None)
def home(request):
    if request.method == 'POST':
        author = request.user
        content = request.POST['tweet']
        tweet = Tweet(author=author, content=content)
        tweet.save()

        for follower in request.user.following.all().values_list('following_user_id', flat=True):
            Notification.objects.create(sender = request.user, receiver = User.objects.get(id=follower), target = tweet, type = 'L')

        return redirect('home')
    else:
        followedUsers = [request.user]
        for followed in request.user.followers.all():
            followedUsers.append(User.objects.get(id=followed.user_id_id))
        
        tweets = Tweet.objects.filter(author__in=followedUsers).order_by('-timeStamp')
        
        rec_profiles = User.objects.annotate(count=Count('followers')).order_by('followers').exclude(username=request.user.username).exclude(id__in=request.user.followers.all().values_list('user_id', flat=True))[:5]

        return render(request, 'home.html', {'tweets':tweets, 'rec_profiles':rec_profiles})

def profile(request, username):
    if request.method == 'POST':
        user = User.objects.get(username=username)

        user.profile.bio = request.POST['bio']
        user.profile.profilePic = request.FILES['pic'] if 'pic' in request.FILES else user.profile.profilePic
        user.profile.backgroundPic = request.FILES['banner'] if 'banner' in request.FILES else user.profile.backgroundPic

        user.save()
        return redirect('profile', username=username)
    else:
        try:
            userProfile = User.objects.get(username=username)
        except User.DoesNotExist:
            return HttpResponse('User Not Found')

        tweets = Tweet.objects.filter(author__exact=userProfile).order_by('-timeStamp')

        is_following = False
        for follow in request.user.followers.all():
            if userProfile.id == follow.user_id_id:
                is_following=True

        rec_profiles = User.objects.annotate(count=Count('followers')).order_by('followers').exclude(username=request.user.username).exclude(username=username).exclude(id__in=request.user.followers.all().values_list('user_id', flat=True))[:5]

        return render(request, 'profile.html', {'userProfile':userProfile, 'tweets':tweets, 'is_following':is_following, 'rec_profiles':rec_profiles})

@login_required(redirect_field_name=None)
def delete_post(request, tweetID):
    if request.method == 'POST':
        tweet = Tweet.objects.get(id=tweetID)
        if tweet.author == request.user:
            tweet.delete()
        return redirect('profile', username=request.user.username)
    else:
        return redirect('home')

@login_required(redirect_field_name=None)
def like_post(request):
    tweet = get_object_or_404(Tweet, id=request.POST.get('id'))
    
    if tweet.likes.filter(id=request.user.id).exists():
        tweet.likes.remove(request.user)
        is_liked = False
    else:
        tweet.likes.add(request.user)
        is_liked = True

        if(request.user != tweet.author):
            Notification.objects.create(sender = request.user, receiver = User.objects.get(username = tweet.author), target = tweet, type = 'L')
            
    context = {
        'tweet': tweet,
        'is_liked': is_liked,
    }

    if request.is_ajax():
        html = render_to_string('tweet.html', context, request=request)
        return JsonResponse({'form':html})

@login_required(redirect_field_name=None)
def change_mode(request):
    if request.method == 'POST':
        usr = User.objects.get(id=request.user.id)
        usr.profile.mode = request.POST['mode']
        usr.save()
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
    else:
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

@login_required(redirect_field_name=None)
def follow_profile(request):
    followed_user = get_object_or_404(User, id=request.POST.get('id'))

    if Follow.objects.filter(user_id=followed_user.id, following_user_id = request.user.id).exists():
        Follow.objects.filter(user_id=followed_user.id, following_user_id = request.user.id).delete()
        is_following = False
    else:
        Follow.objects.create(user_id=followed_user, following_user_id = request.user)
        Notification.objects.create(sender = request.user, receiver = followed_user, target = None, type = 'F')
        is_following = True

    context = {
        'profile':followed_user,
        'userProfile':followed_user,
        'is_following':is_following
    }

    if request.is_ajax():
        html = render_to_string('follow_button.html', context, request=request)
        return JsonResponse({'form':html})


def notifications(request):
    notifics = request.user.your_notifications.all()
    for notific in notifics:
        notific.seen = True
        notific.save()
    notifics = request.user.your_notifications.all().order_by('-id')[:10]
    return render(request, 'notifications.html', {'notifics':notifics})


def tweet_details(request, tweetID):
    tweet = Tweet.objects.get(id=tweetID)
    comments = tweet.main_tweet.all().order_by('-timeStamp')
    
    return render(request, 'tweet_details.html', {'tweet':tweet, 'comments':comments})


def comment(request, tweetID):
    if request.method == 'POST':
        author = request.user
        content = request.POST['comment']
        tweet = Tweet.objects.get(id=tweetID)
        Comment.objects.create(author=author, main_tweet=tweet, content=content)

        if(request.user != tweet.author):
            Notification.objects.create(sender = request.user, receiver = tweet.author, target = tweet, type = 'C')
        return redirect(tweet_details, tweetID=tweetID)
    else:
        return redirect(home)

#Notification on post comment
[((68, 1, 68, 41), 'django.contrib.auth.decorators.login_required', 'login_required', (), '', False, 'from django.contrib.auth.decorators import login_required\n'), ((118, 1, 118, 41), 'django.contrib.auth.decorators.login_required', 'login_required', (), '', False, 'from django.contrib.auth.decorators import login_required\n'), ((128, 1, 128, 41), 'django.contrib.auth.decorators.login_required', 'login_required', (), '', False, 'from django.contrib.auth.decorators import login_required\n'), ((151, 1, 151, 41), 'django.contrib.auth.decorators.login_required', 'login_required', (), '', False, 'from django.contrib.auth.decorators import login_required\n'), ((161, 1, 161, 41), 'django.contrib.auth.decorators.login_required', 'login_required', (), '', False, 'from django.contrib.auth.decorators import login_required\n'), ((20, 11, 20, 40), 'django.shortcuts.render', 'render', ({(20, 18, 20, 25): 'request', (20, 27, 20, 39): '"""index.html"""'}, {}), "(request, 'index.html')", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((41, 4, 41, 25), 'django.contrib.auth.logout', 'auth_logout', ({(41, 16, 41, 24): 'reqeuest'}, {}), '(reqeuest)', True, 'from django.contrib.auth import authenticate, logout as auth_logout, login as auth_login\n'), ((42, 11, 42, 28), 'django.shortcuts.redirect', 'redirect', ({(42, 20, 42, 27): '"""index"""'}, {}), "('index')", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((190, 11, 190, 71), 'django.shortcuts.render', 'render', ({(190, 18, 190, 25): 'request', (190, 27, 190, 47): '"""notifications.html"""', (190, 49, 190, 70): "{'notifics': notifics}"}, {}), "(request, 'notifications.html', {'notifics': notifics})", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((194, 12, 194, 41), 'twitter.models.Tweet.objects.get', 'Tweet.objects.get', (), '', False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((197, 11, 197, 86), 'django.shortcuts.render', 'render', ({(197, 18, 197, 25): 'request', (197, 27, 197, 47): '"""tweet_details.html"""', (197, 49, 197, 85): "{'tweet': tweet, 'comments': comments}"}, {}), "(request, 'tweet_details.html', {'tweet': tweet, 'comments': comments})", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((38, 15, 38, 44), 'django.shortcuts.render', 'render', ({(38, 22, 38, 29): 'request', (38, 31, 38, 43): '"""login.html"""'}, {}), "(request, 'login.html')", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((65, 15, 65, 27), 'twitter.forms.SignUpForm', 'SignUpForm', ({}, {}), '()', False, 'from twitter.forms import SignUpForm\n'), ((66, 15, 66, 62), 'django.shortcuts.render', 'render', ({(66, 22, 66, 29): 'request', (66, 31, 66, 46): '"""register.html"""', (66, 48, 66, 61): "{'form': form}"}, {}), "(request, 'register.html', {'form': form})", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((73, 16, 73, 53), 'twitter.models.Tweet', 'Tweet', (), '', False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((79, 15, 79, 31), 'django.shortcuts.redirect', 'redirect', ({(79, 24, 79, 30): '"""home"""'}, {}), "('home')", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((89, 15, 89, 91), 'django.shortcuts.render', 'render', ({(89, 22, 89, 29): 'request', (89, 31, 89, 42): '"""home.html"""', (89, 44, 89, 90): "{'tweets': tweets, 'rec_profiles': rec_profiles}"}, {}), "(request, 'home.html', {'tweets': tweets, 'rec_profiles': rec_profiles})", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((93, 15, 93, 50), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', (), '', False, 'from django.contrib.auth.models import User\n'), ((100, 15, 100, 53), 'django.shortcuts.redirect', 'redirect', (), '', False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((116, 15, 116, 150), 'django.shortcuts.render', 'render', ({(116, 22, 116, 29): 'request', (116, 31, 116, 45): '"""profile.html"""', (116, 47, 116, 149): "{'userProfile': userProfile, 'tweets': tweets, 'is_following': is_following,\n    'rec_profiles': rec_profiles}"}, {}), "(request, 'profile.html', {'userProfile': userProfile, 'tweets':\n    tweets, 'is_following': is_following, 'rec_profiles': rec_profiles})", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((121, 16, 121, 45), 'twitter.models.Tweet.objects.get', 'Tweet.objects.get', (), '', False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((124, 15, 124, 66), 'django.shortcuts.redirect', 'redirect', (), '', False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((126, 15, 126, 31), 'django.shortcuts.redirect', 'redirect', ({(126, 24, 126, 30): '"""home"""'}, {}), "('home')", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((148, 15, 148, 71), 'django.template.loader.render_to_string', 'render_to_string', (), '', False, 'from django.template.loader import render_to_string\n'), ((149, 15, 149, 42), 'django.http.JsonResponse', 'JsonResponse', ({(149, 28, 149, 41): "{'form': html}"}, {}), "({'form': html})", False, 'from django.http import HttpResponseRedirect, JsonResponse\n'), ((154, 14, 154, 50), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', (), '', False, 'from django.contrib.auth.models import User\n'), ((169, 8, 169, 86), 'twitter.models.Follow.objects.create', 'Follow.objects.create', (), '', False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((170, 8, 170, 111), 'twitter.models.Notification.objects.create', 'Notification.objects.create', (), '', False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((180, 15, 180, 79), 'django.template.loader.render_to_string', 'render_to_string', (), '', False, 'from django.template.loader import render_to_string\n'), ((181, 15, 181, 42), 'django.http.JsonResponse', 'JsonResponse', ({(181, 28, 181, 41): "{'form': html}"}, {}), "({'form': html})", False, 'from django.http import HttpResponseRedirect, JsonResponse\n'), ((204, 16, 204, 45), 'twitter.models.Tweet.objects.get', 'Tweet.objects.get', (), '', False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((205, 8, 205, 80), 'twitter.models.Comment.objects.create', 'Comment.objects.create', (), '', False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((209, 15, 209, 55), 'django.shortcuts.redirect', 'redirect', (), '', False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((211, 15, 211, 29), 'django.shortcuts.redirect', 'redirect', ({(211, 24, 211, 28): 'home'}, {}), '(home)', False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((28, 19, 28, 69), 'django.contrib.auth.authenticate', 'authenticate', (), '', False, 'from django.contrib.auth import authenticate, logout as auth_logout, login as auth_login\n'), ((48, 19, 48, 36), 'django.shortcuts.redirect', 'redirect', ({(48, 28, 48, 35): '"""index"""'}, {}), "('index')", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((103, 26, 103, 61), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', (), '', False, 'from django.contrib.auth.models import User\n'), ((165, 7, 165, 91), 'twitter.models.Follow.objects.filter', 'Follow.objects.filter', (), '', False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((208, 12, 208, 115), 'twitter.models.Notification.objects.create', 'Notification.objects.create', (), '', False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((30, 16, 30, 41), 'django.contrib.auth.login', 'auth_login', ({(30, 27, 30, 34): 'request', (30, 36, 30, 40): 'user'}, {}), '(request, user)', True, 'from django.contrib.auth import authenticate, logout as auth_logout, login as auth_login\n'), ((31, 23, 31, 39), 'django.shortcuts.redirect', 'redirect', ({(31, 32, 31, 38): '"""home"""'}, {}), "('home')", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((33, 16, 33, 62), 'django.contrib.messages.error', 'messages.error', ({(33, 31, 33, 38): 'request', (33, 40, 33, 61): '"""Invalid credentials"""'}, {}), "(request, 'Invalid credentials')", False, 'from django.contrib import messages\n'), ((34, 23, 34, 52), 'django.shortcuts.render', 'render', ({(34, 30, 34, 37): 'request', (34, 39, 34, 51): '"""login.html"""'}, {}), "(request, 'login.html')", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((36, 19, 36, 36), 'django.shortcuts.redirect', 'redirect', ({(36, 28, 36, 35): '"""index"""'}, {}), "('index')", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((50, 19, 50, 43), 'twitter.forms.SignUpForm', 'SignUpForm', ({(50, 30, 50, 42): 'request.POST'}, {}), '(request.POST)', False, 'from twitter.forms import SignUpForm\n'), ((83, 33, 83, 73), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', (), '', False, 'from django.contrib.auth.models import User\n'), ((85, 17, 85, 63), 'twitter.models.Tweet.objects.filter', 'Tweet.objects.filter', (), '', False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((105, 19, 105, 49), 'django.http.response.HttpResponse', 'HttpResponse', ({(105, 32, 105, 48): '"""User Not Found"""'}, {}), "('User Not Found')", False, 'from django.http.response import HttpResponse\n'), ((107, 17, 107, 64), 'twitter.models.Tweet.objects.filter', 'Tweet.objects.filter', (), '', False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((166, 8, 166, 92), 'twitter.models.Follow.objects.filter', 'Follow.objects.filter', (), '', False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((57, 23, 57, 85), 'django.contrib.auth.authenticate', 'authenticate', (), '', False, 'from django.contrib.auth import authenticate, logout as auth_logout, login as auth_login\n'), ((58, 16, 58, 41), 'django.contrib.auth.login', 'auth_login', ({(58, 27, 58, 34): 'request', (58, 36, 58, 40): 'user'}, {}), '(request, user)', True, 'from django.contrib.auth import authenticate, logout as auth_logout, login as auth_login\n'), ((59, 23, 59, 39), 'django.shortcuts.redirect', 'redirect', ({(59, 32, 59, 38): '"""home"""'}, {}), "('home')", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((61, 23, 61, 35), 'twitter.forms.SignUpForm', 'SignUpForm', ({}, {}), '()', False, 'from twitter.forms import SignUpForm\n'), ((62, 16, 62, 60), 'django.contrib.messages.error', 'messages.error', ({(62, 31, 62, 38): 'request', (62, 40, 62, 59): '"""Invalid form fill"""'}, {}), "(request, 'Invalid form fill')", False, 'from django.contrib import messages\n'), ((63, 23, 63, 70), 'django.shortcuts.render', 'render', ({(63, 30, 63, 37): 'request', (63, 39, 63, 54): '"""register.html"""', (63, 56, 63, 69): "{'form': form}"}, {}), "(request, 'register.html', {'form': form})", False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((77, 74, 77, 103), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', (), '', False, 'from django.contrib.auth.models import User\n'), ((140, 74, 140, 115), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', (), '', False, 'from django.contrib.auth.models import User\n'), ((87, 51, 87, 69), 'django.db.models.Count', 'Count', ({(87, 57, 87, 68): '"""followers"""'}, {}), "('followers')", False, 'from django.db.models import Count\n'), ((114, 51, 114, 69), 'django.db.models.Count', 'Count', ({(114, 57, 114, 68): '"""followers"""'}, {}), "('followers')", False, 'from django.db.models import Count\n')]