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
[((2489, 2529), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'redirect_field_name': 'None'}), '(redirect_field_name=None)\n', (2503, 2529), False, 'from django.contrib.auth.decorators import login_required\n'), ((4880, 4920), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'redirect_field_name': 'None'}), '(redirect_field_name=None)\n', (4894, 4920), False, 'from django.contrib.auth.decorators import login_required\n'), ((5214, 5254), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'redirect_field_name': 'None'}), '(redirect_field_name=None)\n', (5228, 5254), False, 'from django.contrib.auth.decorators import login_required\n'), ((5963, 6003), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'redirect_field_name': 'None'}), '(redirect_field_name=None)\n', (5977, 6003), False, 'from django.contrib.auth.decorators import login_required\n'), ((6333, 6373), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'redirect_field_name': 'None'}), '(redirect_field_name=None)\n', (6347, 6373), False, 'from django.contrib.auth.decorators import login_required\n'), ((764, 793), 'django.shortcuts.render', 'render', (['request', '"""index.html"""'], {}), "(request, 'index.html')\n", (770, 793), False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((1468, 1489), 'django.contrib.auth.logout', 'auth_logout', (['reqeuest'], {}), '(reqeuest)\n', (1479, 1489), True, 'from django.contrib.auth import authenticate, logout as auth_logout, login as auth_login\n'), ((1501, 1518), 'django.shortcuts.redirect', 'redirect', (['"""index"""'], {}), "('index')\n", (1509, 1518), False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((7472, 7533), 'django.shortcuts.render', 'render', (['request', '"""notifications.html"""', "{'notifics': notifics}"], {}), "(request, 'notifications.html', {'notifics': notifics})\n", (7478, 7533), False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((7584, 7613), 'twitter.models.Tweet.objects.get', 'Tweet.objects.get', ([], {'id': 'tweetID'}), '(id=tweetID)\n', (7601, 7613), False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((7691, 7768), 'django.shortcuts.render', 'render', (['request', '"""tweet_details.html"""', "{'tweet': tweet, 'comments': comments}"], {}), "(request, 'tweet_details.html', {'tweet': tweet, 'comments': comments})\n", (7697, 7768), False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((1411, 1440), 'django.shortcuts.render', 'render', (['request', '"""login.html"""'], {}), "(request, 'login.html')\n", (1417, 1440), False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((2411, 2423), 'twitter.forms.SignUpForm', 'SignUpForm', ([], {}), '()\n', (2421, 2423), False, 'from twitter.forms import SignUpForm\n'), ((2439, 2487), 'django.shortcuts.render', 'render', (['request', '"""register.html"""', "{'form': form}"], {}), "(request, 'register.html', {'form': form})\n", (2445, 2487), False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((2668, 2705), 'twitter.models.Tweet', 'Tweet', ([], {'author': 'author', 'content': 'content'}), '(author=author, content=content)\n', (2673, 2705), False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((2975, 2991), 'django.shortcuts.redirect', 'redirect', (['"""home"""'], {}), "('home')\n", (2983, 2991), False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((3507, 3585), 'django.shortcuts.render', 'render', (['request', '"""home.html"""', "{'tweets': tweets, 'rec_profiles': rec_profiles}"], {}), "(request, 'home.html', {'tweets': tweets, 'rec_profiles': rec_profiles})\n", (3513, 3585), False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((3665, 3700), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', ([], {'username': 'username'}), '(username=username)\n', (3681, 3700), False, 'from django.contrib.auth.models import User\n'), ((4017, 4055), 'django.shortcuts.redirect', 'redirect', (['"""profile"""'], {'username': 'username'}), "('profile', username=username)\n", (4025, 4055), False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((4742, 4885), 'django.shortcuts.render', 'render', (['request', '"""profile.html"""', "{'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})\n", (4748, 4885), False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((5005, 5034), 'twitter.models.Tweet.objects.get', 'Tweet.objects.get', ([], {'id': 'tweetID'}), '(id=tweetID)\n', (5022, 5034), False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((5118, 5169), 'django.shortcuts.redirect', 'redirect', (['"""profile"""'], {'username': 'request.user.username'}), "('profile', username=request.user.username)\n", (5126, 5169), False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((5195, 5211), 'django.shortcuts.redirect', 'redirect', (['"""home"""'], {}), "('home')\n", (5203, 5211), False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((5861, 5917), 'django.template.loader.render_to_string', 'render_to_string', (['"""tweet.html"""', 'context'], {'request': 'request'}), "('tweet.html', context, request=request)\n", (5877, 5917), False, 'from django.template.loader import render_to_string\n'), ((5933, 5961), 'django.http.JsonResponse', 'JsonResponse', (["{'form': html}"], {}), "({'form': html})\n", (5945, 5961), False, 'from django.http import HttpResponseRedirect, JsonResponse\n'), ((6077, 6113), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', ([], {'id': 'request.user.id'}), '(id=request.user.id)\n', (6093, 6113), False, 'from django.contrib.auth.models import User\n'), ((6726, 6802), 'twitter.models.Follow.objects.create', 'Follow.objects.create', ([], {'user_id': 'followed_user', 'following_user_id': 'request.user'}), '(user_id=followed_user, following_user_id=request.user)\n', (6747, 6802), False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((6813, 6912), 'twitter.models.Notification.objects.create', 'Notification.objects.create', ([], {'sender': 'request.user', 'receiver': 'followed_user', 'target': 'None', 'type': '"""F"""'}), "(sender=request.user, receiver=followed_user,\n    target=None, type='F')\n", (6840, 6912), False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((7116, 7180), 'django.template.loader.render_to_string', 'render_to_string', (['"""follow_button.html"""', 'context'], {'request': 'request'}), "('follow_button.html', context, request=request)\n", (7132, 7180), False, 'from django.template.loader import render_to_string\n'), ((7196, 7224), 'django.http.JsonResponse', 'JsonResponse', (["{'form': html}"], {}), "({'form': html})\n", (7208, 7224), False, 'from django.http import HttpResponseRedirect, JsonResponse\n'), ((7921, 7950), 'twitter.models.Tweet.objects.get', 'Tweet.objects.get', ([], {'id': 'tweetID'}), '(id=tweetID)\n', (7938, 7950), False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((7959, 8031), 'twitter.models.Comment.objects.create', 'Comment.objects.create', ([], {'author': 'author', 'main_tweet': 'tweet', 'content': 'content'}), '(author=author, main_tweet=tweet, content=content)\n', (7981, 8031), False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((8206, 8246), 'django.shortcuts.redirect', 'redirect', (['tweet_details'], {'tweetID': 'tweetID'}), '(tweet_details, tweetID=tweetID)\n', (8214, 8246), False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((8272, 8286), 'django.shortcuts.redirect', 'redirect', (['home'], {}), '(home)\n', (8280, 8286), False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((1009, 1059), 'django.contrib.auth.authenticate', 'authenticate', (['request'], {'username': 'mail', 'password': 'pwd'}), '(request, username=mail, password=pwd)\n', (1021, 1059), False, 'from django.contrib.auth import authenticate, logout as auth_logout, login as auth_login\n'), ((1654, 1671), 'django.shortcuts.redirect', 'redirect', (['"""index"""'], {}), "('index')\n", (1662, 1671), False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((4105, 4140), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', ([], {'username': 'username'}), '(username=username)\n', (4121, 4140), False, 'from django.contrib.auth.models import User\n'), ((6482, 6569), 'twitter.models.Follow.objects.filter', 'Follow.objects.filter', ([], {'user_id': 'followed_user.id', 'following_user_id': 'request.user.id'}), '(user_id=followed_user.id, following_user_id=request.\n    user.id)\n', (6503, 6569), False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((8087, 8186), 'twitter.models.Notification.objects.create', 'Notification.objects.create', ([], {'sender': 'request.user', 'receiver': 'tweet.author', 'target': 'tweet', 'type': '"""C"""'}), "(sender=request.user, receiver=tweet.author,\n    target=tweet, type='C')\n", (8114, 8186), False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((1109, 1134), 'django.contrib.auth.login', 'auth_login', (['request', 'user'], {}), '(request, user)\n', (1119, 1134), True, 'from django.contrib.auth import authenticate, logout as auth_logout, login as auth_login\n'), ((1158, 1174), 'django.shortcuts.redirect', 'redirect', (['"""home"""'], {}), "('home')\n", (1166, 1174), False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((1209, 1255), 'django.contrib.messages.error', 'messages.error', (['request', '"""Invalid credentials"""'], {}), "(request, 'Invalid credentials')\n", (1223, 1255), False, 'from django.contrib import messages\n'), ((1279, 1308), 'django.shortcuts.render', 'render', (['request', '"""login.html"""'], {}), "(request, 'login.html')\n", (1285, 1308), False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((1368, 1385), 'django.shortcuts.redirect', 'redirect', (['"""index"""'], {}), "('index')\n", (1376, 1385), False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((1732, 1756), 'twitter.forms.SignUpForm', 'SignUpForm', (['request.POST'], {}), '(request.POST)\n', (1742, 1756), False, 'from twitter.forms import SignUpForm\n'), ((3128, 3168), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', ([], {'id': 'followed.user_id_id'}), '(id=followed.user_id_id)\n', (3144, 3168), False, 'from django.contrib.auth.models import User\n'), ((3196, 3242), 'twitter.models.Tweet.objects.filter', 'Tweet.objects.filter', ([], {'author__in': 'followedUsers'}), '(author__in=followedUsers)\n', (3216, 3242), False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((4194, 4224), 'django.http.response.HttpResponse', 'HttpResponse', (['"""User Not Found"""'], {}), "('User Not Found')\n", (4206, 4224), False, 'from django.http.response import HttpResponse\n'), ((4243, 4290), 'twitter.models.Tweet.objects.filter', 'Tweet.objects.filter', ([], {'author__exact': 'userProfile'}), '(author__exact=userProfile)\n', (4263, 4290), False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((6585, 6672), 'twitter.models.Follow.objects.filter', 'Follow.objects.filter', ([], {'user_id': 'followed_user.id', 'following_user_id': 'request.user.id'}), '(user_id=followed_user.id, following_user_id=request.\n    user.id)\n', (6606, 6672), False, 'from twitter.models import Tweet, Follow, Notification, Comment\n'), ((2043, 2103), 'django.contrib.auth.authenticate', 'authenticate', (['request'], {'username': 'email', 'password': 'raw_password'}), '(request, username=email, password=raw_password)\n', (2055, 2103), False, 'from django.contrib.auth import authenticate, logout as auth_logout, login as auth_login\n'), ((2122, 2147), 'django.contrib.auth.login', 'auth_login', (['request', 'user'], {}), '(request, user)\n', (2132, 2147), True, 'from django.contrib.auth import authenticate, logout as auth_logout, login as auth_login\n'), ((2171, 2187), 'django.shortcuts.redirect', 'redirect', (['"""home"""'], {}), "('home')\n", (2179, 2187), False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((2229, 2241), 'twitter.forms.SignUpForm', 'SignUpForm', ([], {}), '()\n', (2239, 2241), False, 'from twitter.forms import SignUpForm\n'), ((2258, 2302), 'django.contrib.messages.error', 'messages.error', (['request', '"""Invalid form fill"""'], {}), "(request, 'Invalid form fill')\n", (2272, 2302), False, 'from django.contrib import messages\n'), ((2326, 2374), 'django.shortcuts.render', 'render', (['request', '"""register.html"""', "{'form': form}"], {}), "(request, 'register.html', {'form': form})\n", (2332, 2374), False, 'from django.shortcuts import get_object_or_404, redirect, render\n'), ((2900, 2929), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', ([], {'id': 'follower'}), '(id=follower)\n', (2916, 2929), False, 'from django.contrib.auth.models import User\n'), ((5659, 5698), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', ([], {'username': 'tweet.author'}), '(username=tweet.author)\n', (5675, 5698), False, 'from django.contrib.auth.models import User\n'), ((3326, 3344), 'django.db.models.Count', 'Count', (['"""followers"""'], {}), "('followers')\n", (3331, 3344), False, 'from django.db.models import Count\n'), ((4534, 4552), 'django.db.models.Count', 'Count', (['"""followers"""'], {}), "('followers')\n", (4539, 4552), False, 'from django.db.models import Count\n')]