from comperio.main.tools import render, MessageManager
from comperio.curricula.forms import CreateCurriculumForm, CreateLessonForm
from comperio.curricula.models import Curriculum, Lesson
from django.shortcuts import redirect, get_object_or_404

def create_curriculum(request):
    """create a new curriculum container"""
    mm = MessageManager(request)
    if request.POST:
        form = CreateCurriculumForm(request.POST)
        if form.is_valid():
            # save it
            c = form.save(request)
            mm.set_success("the curriculum was saved")
            return redirect(c.get_absolute_url())
        else:
            mm.set_error("the form has errors")
            pass
    else:
        form = CreateCurriculumForm()
    return render(request, 'curricula/create_curriculum.html', {'form':form}, mm.messages())

def view_curriculum(request, id):
    """view a curriculum"""
    mm = MessageManager(request)
    c = get_object_or_404(Curriculum, pk=id)
    lessons = list()
    #lessons.extend(ExternalLesson.objects.filter(curriculum=c))
    lessons = Lesson.objects.filter(curriculum=c).order_by('index', 'pub_date')
    #lessons.extend(DocumentLesson.objects.filter(curriculum=c))
    return render(request, 'curricula/view_curriculum.html', {'curriculum':c, 'lessons':lessons}, mm.messages())

def edit_curriculum(request, id):
    """edit a curriculum"""
    mm = MessageManager(request)
    c = get_object_or_404(Curriculum, pk=id)
    if request.user.is_authenticated() and request.user.username == c.user.username:
        if request.POST:
            form = CreateCurriculumForm(request.POST)
            if form.is_valid():
                # update it
                c = form.update(request, c)
                mm.set_success('"%s" has been updated' % c.title)
                return redirect(c.get_absolute_url())
            else:
                mm.set_error("the form has errors")
                pass
        else:
            form = CreateCurriculumForm(initial={'title':c.title, 'description':c.description})
        return render(request, 'curricula/edit_curriculum.html', {'form':form, 'curriculum':c}, mm.messages())
    else:
        mm.set_notice('You are not authorized to edit that curriculum')
        return redirect(request.META.get('HTTP_REFERER','/'))

def delete_curriculum(request, id):
    """delete an existing curriculum"""
    mm = MessageManager(request)
    c = get_object_or_404(Curriculum, pk=id)
    if request.user.is_authenticated() and request.user.username == c.user.username:
        c.delete()
        return redirect(request.user.get_absolute_url())
    else:
        mm.set_notice('you are not authorized to delete this curriculum')
        return redirect(c.get_absolute_url())
        
def create_lesson(request, c_id):
    """create a new lesson"""
    c = get_object_or_404(Curriculum, pk=c_id)
    mm = MessageManager(request)
    if request.POST:
        form = CreateLessonForm(request.POST)
        if form.is_valid():
            # save it
            l = form.save(request, c)
            mm.set_success("the lesson was saved")
            return redirect(c.get_absolute_url())
        else:
            mm.set_error("the form has errors")
            pass
    else:
        form = CreateLessonForm()
    return render(request, 'curricula/create_lesson.html', {'form':form, 'curriculum':c}, mm.messages())

def delete_lesson(request, c_id, l_id):
    """delete an existing lesson"""
    mm = MessageManager(request)
    l = get_object_or_404(Lesson, pk=l_id)
    c = get_object_or_404(Curriculum, pk=c_id)
    if request.user.is_authenticated() and request.user.username == l.user.username:
        name = l.title
        l.delete()
        mm.set_success('"%s" has been deleted' % name)
    else:
        mm.set_notice('you are not authorized to delete this lesson')
    return redirect(c.get_absolute_url())
    
def view_lesson(request, c_id, l_id):
    """view a lesson"""
    mm = MessageManager(request)
    c = get_object_or_404(Curriculum, pk=c_id)
    l = get_object_or_404(Lesson, pk=l_id)
    return render(request, 'curricula/view_lesson.html', {'curriculum':c, 'lesson':l}, mm.messages())

def edit_lesson(request, c_id, l_id):
    """edit a lesson"""
    mm = MessageManager(request)
    c = get_object_or_404(Curriculum, pk=c_id) # we don't need both curriculum and lesson id because we are moving towards just using the custom lesson model
    l = get_object_or_404(Lesson, pk=l_id)
    if request.user.is_authenticated() and request.user.username == l.user.username:
        if request.POST:
            form = CreateLessonForm(request.POST)
            if form.is_valid():
                # update it
                l = form.update(request, l)
                mm.set_success('"%s" has been updated' % l.title)
                return redirect(l.get_absolute_url())
            else:
                mm.set_error("the form has errors")
                pass
        else:
            form = CreateLessonForm(initial={'title':l.title, 'description':l.description, 'body':l.body})
        return render(request, 'curricula/edit_lesson.html', {'form':form, 'lesson':l, 'curriculum':c}, mm.messages())
    else:
        mm.set_notice('You are not authorized to edit that curriculum')
        return redirect(request.META.get('HTTP_REFERER','/'))

def down_lesson_index(request, c_id, l_id):
    """move a lesson down in the list"""
    # get curriculum
    try:
        c = Curriculum.objects.get(pk=c_id)
    except Curriculum.DoesNotExist:
        return redirect(request.META.get('HTTP_REFERER','/'))
        
    # get lesson
    try:
        lesson = Lesson.objects.get(pk=l_id, curriculum=c)
    except Lesson.DoesNotExist:
        return redirect(request.META.get('HTTP_REFERER','/'))
    
    # validate user
    if not (request.user.is_authenticated() and request.user.username == lesson.user.username):
        return redirect(request.META.get('HTTP_REFERER','/'))
    
    # get any conflicting lessons
    try:
        conflict = Lesson.objects.get(index=lesson.index + 1, curriculum=c)
    except Lesson.DoesNotExist:
        # no conflicts :)
        conflict = None
    
    # cap ends so we don't get huge indexes by over clicking
    # TODO: manage conflicts here as well
    lesson_count = Lesson.objects.filter(curriculum=c).count()
    print lesson_count
    if lesson.index + 1 >= lesson_count:
        lesson.index = lesson_count - 1
        lesson.save()
        return redirect(request.META.get('HTTP_REFERER','/'))
    elif lesson.index + 1 < 0:
        lesson.index = 0
        lesson.save()
        return redirect(request.META.get('HTTP_REFERER','/'))
    
    # manage any conflicts
    if conflict:
        temp = conflict.index
        conflict.index = lesson.index
        lesson.index = temp
        lesson.save()
        conflict.save()
    else:
        lesson.index += 1
        lesson.save()
    return redirect(request.META.get('HTTP_REFERER','/'))
    
def up_lesson_index(request, c_id, l_id):
    """move a lesson up in the list"""
    # get curriculum
    try:
        c = Curriculum.objects.get(pk=c_id)
    except Curriculum.DoesNotExist:
        return redirect(request.META.get('HTTP_REFERER','/'))
        
    # get lesson
    try:
        lesson = Lesson.objects.get(pk=l_id, curriculum=c)
    except Lesson.DoesNotExist:
        return redirect(request.META.get('HTTP_REFERER','/'))
    
    # validate user
    if not (request.user.is_authenticated() and request.user.username == lesson.user.username):
        return redirect(request.META.get('HTTP_REFERER','/'))
        
    # get any conflicting lessons
    try:
        conflict = Lesson.objects.get(index=lesson.index - 1, curriculum=c)
    except Lesson.DoesNotExist:
        # no conflicts :)
        conflict = None
        pass
    
    # cap ends so we don't get huge indexes by over clicking
    # TODO: manage conflicts here as well
    lesson_count = Lesson.objects.filter(curriculum=c).count()
    print lesson_count
    if lesson.index - 1 >= lesson_count:
        lesson.index = lesson_count - 1
        lesson.save()
        return redirect(request.META.get('HTTP_REFERER','/'))
    elif lesson.index - 1 < 0:
        lesson.index = 0
        lesson.save()
        return redirect(request.META.get('HTTP_REFERER','/'))
    
    # manage any conflicts
    if conflict:
        temp = conflict.index
        conflict.index = lesson.index
        lesson.index = temp
        lesson.save()
        conflict.save()
    else:
        lesson.index -= 1
        lesson.save()
    return redirect(request.META.get('HTTP_REFERER','/'))
    
    