# -*- coding: utf-8 -*-
from django.db.models import Q
from django.core.urlresolvers import reverse
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.shortcuts import render, render_to_response, get_object_or_404, redirect
from django.template import RequestContext
from django.conf import settings
from django.utils import timezone

from django.contrib.sites.models import get_current_site

from texting.models import Client, ClientLogo, Category, Offer, Contest
from texting.forms import ClientForm, CategoryForm, OfferForm, ContestForm


def _get_site_account_id(request):
    site = get_current_site(request)
    try:
        account_id = site.profile.vibes_account_id
    except AttributeError:
        account_id = getattr(settings, 'TEXTING_VIBES_ACCOUNT_ID', None)
    return account_id


def tabs_home(request):
    today = timezone.now().date()
    current_site = get_current_site(request)
    
    contests = Contest.objects.filter(sites=current_site, startdate__lte=today, enddate__gte=today)
    featured_contests = contests.filter(client__featured=True)
    offers = Offer.objects.filter(sites=current_site, startdate__lte=today, enddate__gte=today)    
    featured_offers = offers.filter(client__featured=True)    
    
    return render(request, 'texting/tabs_home.html', {
        'contests': contests,
        'featured_contests': featured_contests,
        'offers': offers,
        'featured_offers': featured_offers,
        'account_id': _get_site_account_id(request),
    })
    
    
def home(request):
    current_site = get_current_site(request)
    contests = Contest.objects.filter(sites=current_site)
    offers = Offer.objects.filter(sites=current_site)
    return render(request, 'texting/home.html',
        {'contests': contests, 'offers': offers})


def client_list(request):
    current_site = get_current_site(request)
    return render(request, 'texting/client_list.html',
        {
            'client_list': Client.objects.filter(
                Q(offer__sites=current_site) |
                Q(contest__sites=current_site)
            ).distinct(),
        }
    )

def clients_manage(request):
    paginator = Paginator(Client.objects.filter(
        Q(offer__sites=get_current_site(request)) |
        Q(contest__sites=get_current_site(request))
    ).distinct().order_by('name'), 25)
    try:
        page_num = int(request.GET.get('page', 1))
    except ValueError:
        page_num = 1
    try:
        clients = paginator.page(page_num)
    except (EmptyPage, InvalidPage):
        clients = paginator.page(paginator.num_pages)
    return render(request, 'texting/client_manage.html', {'clients': clients})

def client_detail(request, client_id=None):
    current_site = get_current_site(request)
    client = get_object_or_404(Client, pk=client_id)
    offers = Offer.objects.filter(client=client, sites=current_site)
    contests = Contest.objects.filter(client=client, sites=current_site)
    return render(request, 'texting/client_detail.html',
        {'client': client, 'offers': offers, 'contests': contests})


def client_edit(request, client_id=None, **kwargs):
    template_name = kwargs.get("template_name", "texting/client_edit.html")
    
    if client_id:
        client = get_object_or_404(Client, pk=client_id)
    else:
        client = None
    
    if request.method =='POST':
        client_form = ClientForm(request.POST, request.FILES, instance=client)
        if client_form.is_valid():
            client_form.save()
            return redirect('texting_clients_manage')
    else:
        client_form = ClientForm(instance=client)
       
    return render_to_response(
        template_name,
        {'client_form': client_form, 'client': client},
        context_instance=RequestContext(request)
    )


def offers_list(request):
    offers = Offer.objects.filter(sites=get_current_site(request))
    featured_offers = offers.filter(client__featured=True)
    return render(request, 'texting/offers_list.html', {
        'offers': offers,
        'featured_offers': featured_offers,
        'account_id': _get_site_account_id(request),
    })


def offers_manage(request):
    paginator = Paginator(Offer.objects.filter(sites=get_current_site(request)).order_by('-enddate'), 25)
    try:
        page_num = int(request.GET.get('page', 1))
    except ValueError:
        page_num = 1
    try:
        offers = paginator.page(page_num)
    except (EmptyPage, InvalidPage):
        offers = paginator.page(paginator.num_pages)
    return render(request, 'texting/offers_manage.html', {'offers': offers})


def offer_edit(request, offer_id=None):
    if offer_id:
        offer = get_object_or_404(Offer, pk=offer_id)
    else:
        offer = None
    
    if request.method =='POST':
        offer_form = OfferForm(request.POST, instance=offer)
        if offer_form.is_valid():
            offer_form.save()
            return redirect('texting_offers_manage')
    else:
        offer_form = OfferForm(instance=offer)
       
    return render(request, 'texting/offer_edit.html',
        {'offer_form': offer_form, 'offer': offer})
 

def contests_list(request):
    contests = Contest.objects.filter(sites=get_current_site(request))
    featured_contests = contests.filter(client__featured=True)
    return render(request, 'texting/contests_list.html', {
        'contests': contests,
        'featured_contests': featured_contests,
        'account_id': _get_site_account_id(request),
    })


def contests_manage(request):
    paginator = Paginator(Contest.objects.order_by('-enddate'), 25)
    try:
        page_num = int(request.GET.get('page', 1))
    except ValueError:
        page_num = 1
    try:
        contests = paginator.page(page_num)
    except (EmptyPage, InvalidPage):
        contests = paginator.page(paginator.num_pages)
    return render(request, 'texting/contests_manage.html', {'contests': contests})


def contest_edit(request, contest_id=None):
    if contest_id:
        contest = get_object_or_404(Contest, pk=contest_id)
    else:
        contest = None
    
    if request.method =='POST':
        contest_form = ContestForm(request.POST, request.FILES, instance=contest)
        if contest_form.is_valid():
            contest_form.save()
            return redirect('texting_contests_manage')
    else:
        contest_form = ContestForm(instance=contest)
       
    return render(request, 'texting/contest_edit.html',
        {'contest_form': contest_form, 'contest': contest})
 

def category_edit(request, category_id=None, **kwargs):
    template_name = kwargs.get("template_name", "texting/category_edit.html")
    
    if category_id:
        category = get_object_or_404(Category, pk=category_id)
    else:
        category = None
    
    if request.method =='POST':
        category_form = CategoryForm(request.POST, instance=category)
        if category_form.is_valid():
            category_form.save()
            return redirect('texting_home')
    else:
        category_form = CategoryForm(instance=category)
       
    return render_to_response(
        template_name,
        {'category_form': category_form, 'category': category},
        context_instance=RequestContext(request)
    )
