from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from .models import Post, CustomUser
from taggit.models import Tag
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from .forms import PostForm, NewTagForm
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth import authenticate, login, logout
from django.db.models import Q
import sys
import collections
from taggit_templatetags2.views import TagCanvasListView
from django.contrib.auth.models import User
from django.contrib import messages
from post_office import mail



import logging
import mysite.settings
import operator


def navlogin(request):

    log = logging.getLogger('mysite')
    logout(request)
    error = ""
    if request.POST:
        username = request.POST.get("username", "?")
        password = request.POST.get("password", "?")

        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return redirect(mysite.settings.LOGIN_REDIRECT_URL)
            else:
                log.info("Inactive user {} tried to login".format(username))
                error = "Ihre Benutzerkennung wurde deaktiviert."
        else:
            log.info("Login failed for {}".format(username))
            error = "Benutzername oder Kennwort falsch."
    context = {'error': error}
    return render(request, 'index.html', context)


@login_required
def post_list(request, slug=None):
    log = logging.getLogger('mysite')
    posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    if slug:
        tag = get_object_or_404(Tag, slug=slug)
        posts = posts.filter(tags__in=[tag])
        log.info(posts)
    return render(request, 'post_list.html', locals())


@login_required
def post_detail(request, pk):
    post = get_object_or_404(Post, pk=pk)
    return render(request, 'post_detail.html', {'post': post})


@login_required
@staff_member_required
def post_new(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.save()
            return redirect('post_detail', pk=post.pk)
    else:
        form = PostForm()
    return render(request, 'post_edit.html', {'form': form})


@login_required
@staff_member_required
def post_edit(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.save()
            form.save_m2m()
            return redirect('post_detail', pk=post.pk)
    else:
        form = PostForm(instance=post)
    return render(request, 'post_edit.html', {'form': form})


@login_required
@staff_member_required
def post_draft_list(request):
    posts = Post.objects.filter(
        published_date__isnull=True).order_by('created_date')
    return render(request, 'post_draft_list.html', {'posts': posts})


@login_required
@staff_member_required
def post_publish(request, pk):
    post = get_object_or_404(Post, pk=pk)
    post.publish()
    return redirect('post_detail', pk=pk)


@login_required
@staff_member_required
def post_remove(request, pk):
    post = get_object_or_404(Post, pk=pk)
    post.delete()
    return redirect('post_list')


@login_required
def tag_remove(request, slug=None):
    if slug:
        tag = get_object_or_404(Tag, slug=slug)
        tag.delete()
        save_m2m()
    return redirect('student_page')

@login_required
def student_page(request):
    user_instance = get_object_or_404(CustomUser, user=request.user)
    if request.method == "POST":
        form = NewTagForm(request.POST, instance=user_instance)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.user = request.user
            obj.save()
            m_tags = form.cleaned_data['m_tags']
            tags = Tag.objects.all()
            if m_tags in tags:
                obj.tags.add(*m_tags)
                form.save_m2m()
                return redirect('/student/')
            else:
                messages.info(request, 'Sorry !! Den Tag den du suchst gibt es leider nicht!')
    else:
        form = NewTagForm()
    return render(request, 'student_page.html', {'form':form})

@login_required
def tag_list(request):
    log = logging.getLogger('mysite')
    u = User.objects.get(username=request.user)
    if u:
        tags_user = Tag.objects.filter(customuser__user = u)
        log.info(tags_user)
    for tag in tags_user:
        posts = Post.objects.filter(tags__in=[tag]).order_by('-published_date')
        log.info(posts)
    return render(request, 'tag_list.html', locals())

class TagSearch(TagCanvasListView):
    template_name = 'blog_search_list_view.html'
    model = Post
    context_object_name = 'list'
    paginate_by = 8
    
    def get_context_data(self, **kwargs):
        context = super(CustomerSearch, self).get_context_data(**kwargs)
        context = self.get_queryset()
        return context

    def get_queryset(self):
        cObj = Customer.objects.all()
        var_get_search = self.request.GET.get('search_box')

        if var_get_search is not None:
            cObj = cObj.filter(firstname__icontains=var_get_search)
        if var_get_order_by is not None:
            cObj = cObj.order_by(var_get_order_by)
        return cObj
        
def blog_search_list_view(request):    
    log = logging.getLogger('mysite')
    posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    if request.method == 'GET':
        search_query = request.GET.get('search_box', None)
        log.info(search_query)
        posts = posts.filter(tags__name__in=[search_query])
    return render(request, 'blog_search_list_view.html', locals())

def tag_cloud(request):
    return render(request, 'tag_cloud.html', {})

mail.send(
    'esther.kleinhenz@web.de', # List of email addresses also accepted
    'esther.kleinhenz@web.de',
    subject='My email',
    message='Hi there!',
    html_message='Hi <strong>there</strong>!',
)
