from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from .models import Post
from .forms import PostForm
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 logging
import mysite.settings
import operator


# Create your views here.


def navlogin(request):

    log = logging.getLogger('medinf')
    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):
    posts = Post.objects.filter(
        published_date__lte=timezone.now()).order_by('published_date')
    return render(request, 'post_list.html', {'posts': posts})


@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()
            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 student_page(request):
    return render(request, 'student_page.html', {})

""" Search for querys
def blog_search_list_view(post_list, self):
    result = super(post_list, self).get_queryset()
    query = self.request.GET.get('q')
    if query:
        query_list = query.split()
        result = result.filter(
            reduce(operator.and_,
            (Q(title__icontains=q) for q in query_list)) |
            reduce(operator.and_,
            (Q(content__icontains=q) for q in query_list))
            )
    return result """