'''
Created on 2010/05/13

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

from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse
from django.db.models import Q
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
from django.views.generic.simple import direct_to_template

from djanction.appauth.decorators import self_item_required
from djanction.item.models import Item, BidLog, ItemModifyLog, QA, ContactMessage
from djanction.item.forms import ItemForm, BidLogForm, ContactMessageForm, ItemModifyForm, ItemSearchForm, QAForm
from djanction.util import ImageUtil
from djanction.appauth.models import User
from djanction.rating.models import FeedbackLog


def item(request):
    if request.method == 'POST':
        return add_item(request)
    elif request.method == 'GET':
        return list(request)


def info(request, item_id=None):
    if request.method == 'POST':
        return mod_item(request, item_id)
    elif request.method == 'GET':
        return item_info(request, item_id)


def item_info(request, item_id=None, template='item/item_detail.html', msg=None):
    model = Item.objects.get(id=item_id)
    form = ItemForm(instance=model)

    if hasattr(settings, 'ICON_TYPE'):
        img_type = settings.ICON_TYPE
    else:
        img_type = 'jpeg'
    image1file = os.path.join(settings.MEDIA_ROOT, 'img', 'items', str(item_id), '1' + '.' + img_type)
    if os.path.isfile(image1file):
        form.image1exist = True
    image2file = os.path.join(settings.MEDIA_ROOT, 'img', 'items', str(item_id), '2' + '.' + img_type)
    if os.path.isfile(image2file):
        form.image2exist = True
    image3file = os.path.join(settings.MEDIA_ROOT, 'img', 'items', str(item_id), '3' + '.' + img_type)
    if os.path.isfile(image3file):
        form.image3exist = True

    min_bid_price = model.start_price
    if model.start_price < model.current_price:
        min_bid_price = model.current_price + settings.ITEM_PRICE_STEP
    if model.prompt_price < min_bid_price:
        min_bid_price = model.prompt_price

    qa_object_list = QA.objects.filter(item=model).order_by('post_date')
    contact_message_object_list = ContactMessage.objects.filter(item=model).order_by('post_date')

    is_auction_owner = False
    is_bidder = False
    if model.user == request.user:
        is_auction_owner = True
    elif model.highest_bidder == request.user:
        is_auction_owner = True
        is_bidder = True

    add_comment_list = ItemModifyLog.objects.filter(item=model).order_by('mod_date')

    is_user_logged_in = False
    if request.user.is_authenticated():
        is_user_logged_in = True

    has_feedback = False
    if model.is_complete:
        item = Item.objects.get(id=item_id)
        if is_bidder:
            has_feedback = FeedbackLog.objects.filter(user=model.user, item=item).count() > 0
        elif is_auction_owner:
            has_feedback = FeedbackLog.objects.filter(user=model.highest_bidder, item=item).count() > 0

    return render_to_response(template, RequestContext(request, {
        'form': form,
        'id': item_id,
        'min_bid_price': min_bid_price,
        'is_auction_owner': is_auction_owner,
        'is_bidder': is_bidder,
        'is_user_logged_in': is_user_logged_in,
        'qa_object_list': qa_object_list,
        'contact_message_object_list': contact_message_object_list,
        'add_comment_list': add_comment_list,
        'has_feedback': has_feedback,
        'msg': msg,
    }))


@login_required
def form(request, item_id=None):
    if item_id:
        return _mod_form(request, item_id)
    else:
        return _add_form(request)


@self_item_required
def _mod_form(request, item_id):
    model = Item.objects.get(id=item_id)
    form = ItemModifyForm()
    if hasattr(settings, 'ICON_TYPE'):
        img_type = settings.ICON_TYPE
    else:
        img_type = 'jpeg'
    image1file = os.path.join(settings.MEDIA_ROOT, 'img', 'items', str(item_id), '1' + '.' + img_type)
    if os.path.isfile(image1file):
        form.image1exist = True
    image2file = os.path.join(settings.MEDIA_ROOT, 'img', 'items', str(item_id), '2' + '.' + img_type)
    if os.path.isfile(image2file):
        form.image2exist = True
    image3file = os.path.join(settings.MEDIA_ROOT, 'img', 'items', str(item_id), '3' + '.' + img_type)
    if os.path.isfile(image3file):
        form.image3exist = True

    return render_to_response('item/form_update.html', RequestContext(request, {
        'model': model,
        'form': form,
        'id': item_id,
    }))


def _add_form(request):
    return render_to_response('item/form.html', RequestContext(request, {
        'form': ItemForm(),
    }))


@login_required
def bids(request, item_id):
    if request.method == 'POST':
        item = Item.objects.get(id=item_id)
        if item.current_price > int(request.POST['current_price']):
            return HttpResponse('status:100')
        if item.is_complete or item.end_date <= datetime.now():
            return HttpResponse('status:101')
        try:
            item.current_price = int(request.POST['bid_price'])
            item.highest_bidder = request.user
            if item.current_price >= item.prompt_price:
                item.is_complete = True
            item.save()
            user = request.user
            bidlog = BidLog()
            bidlog.item = item
            bidlog.user = user
            bidlog.bid_price = request.POST['bid_price']
            bidlog.bid_kind = '0'
            bidlog.save()
        except:
            return HttpResponse('999')

        return HttpResponse('status:000')
        #return render_to_response('item/bid.html', RequestContext(request, {
        #    'form':BidLogForm(instance=bidlog),
        #    'id':item_id,
        #}))
    else:
        return render_to_response('item/bid.html', RequestContext(request, {
            'form':BidLogForm(instance=BidLog()),
            'id':item_id,
            'request':request,
       }))


@login_required
def add_item(request):
    init_item = Item(user=request.user)
    form = ItemForm(request.POST, request.FILES, instance=init_item)

    id = None
    if form.is_valid():
        form.full_clean()
        img_data1 = form.cleaned_data['image1']
        img_data2 = form.cleaned_data['image2']
        img_data3 = form.cleaned_data['image3']

        newmodel = form.save(commit=False)
        newmodel.current_price = newmodel.start_price
        newmodel.save()
        id = newmodel.id
        if img_data1 is not None:
            _save_item_image(img_data1, '1', id)
        if img_data2 is not None:
            _save_item_image(img_data2, '2', id)
        if img_data3 is not None:
            _save_item_image(img_data3, '3', id)
        form = ItemForm(instance=newmodel)

        return HttpResponseRedirect(reverse(info, args=[newmodel.id]))

    else:
        return render_to_response('item/form.html', RequestContext(request, {
            'form': form,
            'id': id,
        }))


@login_required
def mod_item(request, item_id):
    form = ItemModifyForm(request.POST, request.FILES)
    model = Item.objects.get(id=item_id)

    if form.is_valid():
        form.full_clean()
        img_data1 = form.cleaned_data['image1']
        img_data2 = form.cleaned_data['image2']
        img_data3 = form.cleaned_data['image3']
        form.save()
        if img_data1 is not None:
            _save_item_image(img_data1, '1', item_id)
        if img_data2 is not None:
            _save_item_image(img_data2, '2', item_id)
        if img_data3 is not None:
            _save_item_image(img_data3, '3', item_id)

        return HttpResponseRedirect("./")

    else:
        if hasattr(settings, 'ICON_TYPE'):
            img_type = settings.ICON_TYPE
        else:
            img_type = 'jpeg'
        image1file = os.path.join(settings.MEDIA_ROOT, 'img', 'items', str(item_id), '1' + '.' + img_type)
        if os.path.isfile(image1file):
            form.image1exist = True
        image2file = os.path.join(settings.MEDIA_ROOT, 'img', 'items', str(item_id), '2' + '.' + img_type)
        if os.path.isfile(image2file):
            form.image2exist = True
        image3file = os.path.join(settings.MEDIA_ROOT, 'img', 'items', str(item_id), '3' + '.' + img_type)
        if os.path.isfile(image3file):
            form.image3exist = True

        return render_to_response('item/form_update.html', RequestContext(request, {
            'model': model,
            'form': form,
        }))


@login_required
def add_qa(request, item_id=None):
    model = Item.objects.get(id=item_id)

    if request.method == 'POST':
        if not model.is_complete and datetime.now() < model.end_date:
            qa_model = QA(item=model, post_user=request.user)
            qa_form = QAForm(request.POST, instance=qa_model)
            if qa_form.is_valid():
                qa_form.save()

    return HttpResponseRedirect("../")


@login_required
def add_contact_message(request, item_id=None):
    model = Item.objects.get(id=item_id)

    if request.method == 'POST':
        if model.is_complete and model.end_date <= datetime.now():
            contact_message_model = ContactMessage(item=model, post_user=request.user)
            contact_message_form = ContactMessageForm(request.POST, instance=contact_message_model)
            if contact_message_form.is_valid():
                is_auction_owner = False
                if model.user == request.user:
                    is_auction_owner = True
                elif model.highest_bidder == request.user:
                    is_auction_owner = True
                if is_auction_owner:
                    contact_message_form.save()

    return HttpResponseRedirect("../")


def list(request, page_no=1, category_name=None, user_id=None):

    search_query = None
    user_id = None
    form = ItemSearchForm(request.GET)
    if form.is_valid():
        form.full_clean()
        search_query = form.cleaned_data['search_query']
        if search_query == "":
            search_query = None
        user_id = form.cleaned_data['user_id']

    if category_name:
        if search_query:
            if user_id:
                page = Paginator(Item.objects.filter(
                                    _item_Qs(search_query),
                                    is_complete=False,
                                    end_date__gt=datetime.now(),
                                    user=user_id,
                                    category__category_name__startswith=category_name,
                                ).order_by('end_date'), 10).page(page_no)
            else:
                page = Paginator(Item.objects.filter(
                                    _item_Qs(search_query),
                                    is_complete=False,
                                    end_date__gt=datetime.now(),
                                    category__category_name__startswith=category_name,
                                ).order_by('end_date'), 10).page(page_no)
        else:
            if user_id:
                page = Paginator(Item.objects.filter(
                                    is_complete=False,
                                    end_date__gt=datetime.now(),
                                    user=user_id,
                                    category__category_name__startswith=category_name,
                                ).order_by('end_date'), 10).page(page_no)
            else:
                page = Paginator(Item.objects.filter(
                                    is_complete=False,
                                    end_date__gt=datetime.now(),
                                    category__category_name__startswith=category_name,
                                ).order_by('end_date'), 10).page(page_no)
    else:
        category_name = _('all categories')
        if search_query:
            if user_id:
                page = Paginator(Item.objects.filter(
                                    _item_Qs(search_query),
                                    is_complete=False,
                                    end_date__gt=datetime.now(),
                                    user=user_id,
                                ).order_by('end_date'), 10).page(page_no)
            else:
                page = Paginator(Item.objects.filter(
                                    _item_Qs(search_query),
                                    is_complete=False,
                                    end_date__gt=datetime.now(),
                                ).order_by('end_date'), 10).page(page_no)
        else:
            if user_id:
                page = Paginator(Item.objects.filter(
                                    is_complete=False,
                                    end_date__gt=datetime.now(),
                                    user=user_id,
                                ).order_by('end_date'), 10).page(page_no)
            else:
                page = Paginator(Item.objects.filter(
                                    is_complete=False,
                                    end_date__gt=datetime.now(),
                                ).order_by('end_date'), 10).page(page_no)


    esc_search_query = None
    if search_query:
        esc_search_query = urllib.quote(search_query.encode('utf-8'))

    user_name = None
    if user_id:
        o = User
        if o:
            o = o.objects
            if o:
                o = o.get(id=user_id)
                if o:
                    user_name = o.username

    return render_to_response('item/item_list.html', RequestContext(request, {
        'page': page,
        'category': category_name,
        'search_query': search_query,
        'esc_search_query': esc_search_query,
        'user_id': user_id,
        'user_name': user_name,
    }))


def _item_Q(search_query):
    return Q(item_name__icontains=search_query) | Q(comment__icontains=search_query) | Q(search_text__icontains=search_query)


def _item_Qs(search_query):
    query = None
    q_list = search_query.split()
    for q in q_list:
        if query is None:
            query = _item_Q(q)
        else:
            query = query & _item_Q(q)
    return query


@login_required
def contact_detail(request, item_id=None, contact_id=None):
    return None


@login_required
def contact(request, item_id=None):
    return None


@login_required
def cancel(request, item_id=None):
    model = Item.objects.get(id=item_id)

    if model.highest_bidder:
        return direct_to_template(request, 'item/nocancel.html')

    else:
        model.end_date = datetime.now()
        model.is_complete = '1'
        model.save()

        return HttpResponseRedirect(settings.BASE_URL + "/my/selling/")


@login_required
def close(request, item_id=None):
    model = Item.objects.get(id=item_id)

    if model.highest_bidder:
        model.end_date = datetime.now()
        model.is_complete = '1'
        model.save()

        return HttpResponseRedirect(settings.BASE_URL + "/my/selling/")

    else:
        return direct_to_template(request, 'item/noclose.html')

def batch_close():
    from django.db import connection, transaction
    cursor = connection.cursor()
    cursor.execute("update item_item set is_complete=1 where end_date <= %s",[datetime.now()])
    transaction.commit_unless_managed()

@login_required
def qa(request, item_id=None):
    return None


def _save_item_image(img_data, img_name, item_id):
    out_dir = os.path.join(settings.MEDIA_ROOT, 'img', 'items', str(item_id))
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)

    if hasattr(settings, 'ICON_TYPE'):
        img_type = settings.ICON_TYPE
    else:
        img_type = 'jpeg'
    file = img_name + '.' + img_type
    file = os.path.join(out_dir, file)

    img = Image.open(img_data)
    img_width = None
    img_height = None
    if hasattr(settings, 'ITEM_IMG_SIZE'):
        if settings.ITEM_IMG_SIZE.has_key('width'):
            img_width = settings.ITEM_IMG_SIZE['width']
        if settings.ITEM_IMG_SIZE.has_key('height'):
            img_height = settings.ITEM_IMG_SIZE['height']
    else:
        img_width = 600

    img = ImageUtil.resize(img, width=img_width, height=img_height)
    img.save(file, img_type)

    thumb_file = img_name + '_thumb.' + img_type
    thumb_file = os.path.join(out_dir, thumb_file)

    img = Image.open(file)
    img_width = None
    img_height = None
    if hasattr(settings, 'ITEM_THUMB_SIZE'):
        if settings.ITEM_THUMB_SIZE.has_key('width'):
            img_width = settings.ITEM_THUMB_SIZE['width']
        if settings.ITEM_THUMB_SIZE.has_key('height'):
            img_height = settings.ITEM_THUMB_SIZE['height']
    else:
        img_width = 120

    img = ImageUtil.resize(img, width=img_width, height=img_height)
    img.save(thumb_file, img_type)
