'''
Created on 2010/06/27

@author: katsuhiro Inagaki
'''
from djanction.appauth.models import User
from djanction.item.models import Item
from djanction.item.views import item_info
from djanction.rating.forms import FeedbackForm
from djanction.rating.models import FeedbackLog
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext_lazy as _
from django.views.generic.simple import direct_to_template



@login_required
def feedback(request, item_id):
    item = Item.objects.get(id=item_id)
    if item.user == request.user:
        target = item.highest_bidder
    elif item.highest_bidder == request.user:
        target = item.user
    else:
        # TODO don't execute
        pass

    has_feedback = FeedbackLog.objects.filter(user=target, item=item).count() > 0
    if has_feedback:
        msg = _(u'cant\'t do this twice.')
        return item_info(request, item_id, msg=msg)

    if request.method == 'GET':
        form = FeedbackForm()
        return direct_to_template(request, 'item/feedback.html', {
            'item': item,
            'form': form,
            'target': target,
        })
    elif request.method == 'POST':
        form = FeedbackForm(request.POST)
        _add_feedback(form, item, target)
        # TODO result handling
        # TODO go to rating list
        return HttpResponseRedirect(reverse('djanction.item.views.info', args=[item_id]))


def _add_feedback(form, item, target):
    if item.is_complete and form.is_valid():
        # regist feedback
        form.cleaned_data['item'] = item
        form.cleaned_data['item_name'] = item.item_name
        form.cleaned_data['user'] = target
        form.save()
        # update user's rank
        rating = form.cleaned_data['rating']
        if rating < 0:
            target.rank -= 1
        elif 0 < rating:
            target.rank += 1
        target.save()
        return True
    return False


def list_feedback(request, user_id, page_no=1):
    page = Paginator(FeedbackLog.objects.filter(user__id=user_id,).order_by('-regist_date'), 10).page(page_no)
    return direct_to_template(request, 'rating/list.html', {
        'page': page,
        'target': User.objects.get(id=user_id),
    })
