'''
Created on 2010/05/01

@author: katsuhiro Inagaki
'''
from datetime import datetime
import Image
import os

from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.forms.models import modelformset_factory
from django.http import HttpResponseNotAllowed
from django.views.generic.simple import direct_to_template
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core.paginator import Paginator

from djanction.appauth.decorators import self_page_required
from djanction.appauth.models import User, LoginLog
from djanction.mypage import icon_img_type
from djanction.mypage.forms import UserForm, WatchItemForm, WatchItemSearchForm
from djanction.util import ImageUtil
from djanction.watchlist.models import WatchItem
from djanction.item.models import Item


def users(request, user_id=None):
    if request.method == 'GET':
        # todo change here
        return form(request, user_id)
    else:
        return HttpResponseNotAllowed('Only GET Method is allowed.')


@login_required
def form(request, user_id=None):
    my_user_id = user_id
    if user_id is None:
        my_user_id = request.user.id
    return _myform(request, my_user_id)

@self_page_required
def _myform(request, user_id):
    model = User.objects.get(id=user_id)
    form = UserForm(instance=model)
    return direct_to_template(request, 'mypage/profile.html', {
        'form': form,
    })


@login_required
def mymenu(request):
    return direct_to_template(request, 'mypage/mymenu.html')


@login_required
def myprofile(request):
    if request.method == 'POST':
        return _upd_user(request)
    elif request.method == 'GET':
        return direct_to_template(request, 'mypage/profile.html', {
            'form': UserForm(instance=request.user)
        })


def _upd_user(request):
    form = UserForm(request.POST, request.FILES, instance=request.user)
    if form.is_valid():
        form.full_clean()
        icon_data = form.cleaned_data['image']
        if icon_data is not None:
            _save_user_icon(icon_data, request.user.id)
        form.save()
        request.user = User.objects.get(id=request.user.id)
    return direct_to_template(request, 'mypage/profile.html', {
        'form': form,
    })


def _save_user_icon(icon_data, user_id):
    out_dir = os.path.join(settings.MEDIA_ROOT, 'img', 'users', str(user_id))
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)

    file = 'icon.' + icon_img_type()
    file = os.path.join(out_dir, file)

    img = Image.open(icon_data)
    if img.mode != "RGB":
        img = img.convert("RGB")
    icon_width = None
    icon_height = None
    if hasattr(settings, 'USER_ICON_SIZE'):
        if settings.USER_ICON_SIZE.has_key('width'):
            icon_width = settings.USER_ICON_SIZE['width']
        if settings.USER_ICON_SIZE.has_key('height'):
            icon_height = settings.USER_ICON_SIZE['height']
    else:
        icon_width = 120
    img = ImageUtil.resize(img, width=icon_width, height=icon_height)
    img.save(file, icon_img_type())


@login_required
def mypwd_change(request):
    from django.contrib.auth.views import password_change as _password_change
    return _password_change(request,
            template_name = 'mypage/password_change_form.html',
            post_change_redirect = reverse('djanction.mypage.views.myprofile'),
    )


@login_required
def selling(request, page_no=1):
    page = Paginator(Item.objects.filter(is_complete=False,
                                end_date__gt=datetime.now(),
                                user__id=request.user.id
                            ).order_by('end_date'), 10).page(page_no)
    return render_to_response('mypage/selling.html', RequestContext(request, {
        'page': page,
    }))


@login_required
def salesends(request, page_no=1):
    page = Paginator(Item.objects.filter(Q(is_complete=True) | Q(end_date__lte=datetime.now()),
                                user__id=request.user.id
                            ).order_by('end_date'), 10).page(page_no)
    return render_to_response('mypage/salesends.html', RequestContext(request, {
        'page': page,
    }))


def rating(request, user_id=None):
    pass


@login_required
def watchlist(request, page_no=1):
    if request.method == 'POST':
        return _add_watch_item(request)
    elif request.method == 'GET':
        return _list_watch_item(request)


def _list_watch_item(request):
    if request.method == 'GET':
        form = WatchItemSearchForm(request.GET)
    elif request.method == 'POST':
        form = WatchItemSearchForm(request.POST)
    form.is_valid()
    is_complete = form.cleaned_data['is_complete']
    WatchItemFormSet = modelformset_factory(WatchItem, form=WatchItemForm, extra=0)
    if is_complete:
        queryset=WatchItem.objects.filter(
                               Q(item__is_complete=True) | Q(item__end_date__lte=datetime.now()),
                               user=request.user,
                               )
    else:
        queryset=WatchItem.objects.filter(
                               item__is_complete=False,
                               item__end_date__gt=datetime.now(),
                               user=request.user,
                               )
    formset = WatchItemFormSet(queryset=queryset.order_by('item__end_date'))

    return direct_to_template(request, 'mypage/watchlist.html', {
        'is_complete': is_complete,
        'formset': formset,
    })


def _add_watch_item(request):
    form = WatchItemForm(request.POST)
    if not form.is_valid():
        # TODO
        print 'form is not valid'
        pass
    item = form.cleaned_data['item']
    if WatchItem.objects.filter(user=request.user, item=item).count() == 0:
        form.save()

    return direct_to_template(request, 'mypage/watchlist_added.html', {
        'item_id': item.id,
    })


@login_required
def del_watch_item(request):
    WatchItemFormSet = modelformset_factory(WatchItem, form=WatchItemForm, extra=0)
    formset = WatchItemFormSet(request.POST)
    instances = formset.save(commit=False)
    for instance in instances:
        instance.delete()

    return _list_watch_item(request)


@login_required
def biddings(request, page_no=1):
    page = Paginator(Item.objects.filter(is_complete=False, end_date__gt=datetime.now())
                        .extra(
                                where=['exists (select id from item_bidlog where item_bidlog.item_id=item_item.id and item_bidlog.user_id=' + str(request.user.id) + ')']
                               ).order_by('end_date')
                    , 10).page(page_no)
    return render_to_response('mypage/bidding.html', RequestContext(request, {
        'page': page,
        'is_complete': False,
    }))


def successbids(request, page_no=1):
    page = Paginator(Item.objects.filter(Q(is_complete=True) | Q(end_date__lte=datetime.now()),
                                highest_bidder__id=request.user.id
                            ).order_by('end_date'), 10).page(page_no)
    return render_to_response('mypage/bidding.html', RequestContext(request, {
        'page': page,
        'is_complete': True,
    }))


@login_required
def login_log(request):
    list = LoginLog.objects.filter(user=request.user).order_by('-login_date')[:10]
    return direct_to_template(request, 'mypage/login_history.html', {
        'list': list,
    })
