from django.conf import settings
from django.db import transaction
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response, redirect, render, get_object_or_404
from django.template import RequestContext
from polemictweet.models import Group
from polemictweet.forms import GroupForm
from django.utils.translation import ugettext as _, get_language
from django.forms.models import model_to_dict
import sys
import logging

logger = logging.getLogger(__name__)

@transaction.commit_manually
def write_group_base(request, translation_languages, current_language, group_slug=None):
    group = None
    default_language = settings.LANGUAGES[0][0]
    if group_slug:
        instance_group = Group.objects.get(slug=group_slug) #@UndefinedVariable
    else:
        logger.debug("No group_slug") #@UndefinedVariable
        instance_group = None

    form_status = 'none' 
    if request.method == "POST":
        try:
            if instance_group is not None:
                group_instance_val = model_to_dict(instance_group)
            else:
                group_instance_val = {}
            group_form = GroupForm(request.POST, request.FILES, instance = instance_group)
            group_valid = group_form.is_valid()
            logger.debug("write_group_base : valid form: for instance : " + repr(instance_group)) #@UndefinedVariable
            
            if group_valid :               
                if form_status != "error":    
                    group = group_form.save()
                    logger.debug("group : "+str(group))
                    translation_added = False
                
                    #if the user entered translations for title, description or program
                    for language_code in translation_languages :
                        key_title = "title_"+language_code
                        key_description = "description_"+language_code
                        value_title = request.POST.get(key_title)
                        value_description = request.POST.get(key_description)                        
                    
                        if value_title and value_title!="" :
                            translation_added = True
                            logger.debug("title translation exists")
                            if key_title == "title_fr" :
                                group.title_fr = value_title
                            elif key_title == "title_en" :
                                logger.debug("title english exists")
                                group.title_en = value_title
                            else :
                                group.title_ja = value_title

                        if value_description and value_description!="" :
                            translation_added = True
                            if key_description == "description_fr" :
                                group.description_fr = value_description
                            elif key_description == "description_en" :
                                group.description_en = value_description
                            else :
                                group.description_ja = value_description
                        
                    if current_language != default_language :
                        if request.POST.get('title_fr') == '' :
                            translation_added = True
                            group.title_fr = request.POST.get('title')
                        if request.POST.get('description_fr') == '' :
                            translation_added = True
                            group.description_fr = request.POST.get('description')   
                               
                    if translation_added :  
                        group.save()
                    form_status = 'saved'
            else:
                form_status = 'error'
        except Exception, e:
            transaction.rollback()
            __, value, traceback = sys.exc_info()
            return False, False, False, e, traceback
 
    else:
        form_status = 'empty'
        group_form = GroupForm(instance=instance_group)
               
    try:
        transaction.commit()
    except Exception, e:
        transaction.rollback()
        __, __, traceback = sys.exc_info()
        return False, False, False, e, traceback
        
    return group, group_form, form_status, "", ""

def create_group(request, group_slug = None):
    submit_action = request.REQUEST.get("submit_button", False) 
    current_language = get_language().split("-")[0]

    all_languages = settings.LANGUAGES
    translation_languages = []
    
    for l in all_languages:
        if l[0] != current_language:
            translation_languages.append(l[0])
    
    if submit_action=="close":
        return render_to_response('home.html', {'message': "You saved your group", 'translation_languages' : translation_languages, 'current_language' : current_language}, context_instance=RequestContext(request))

    else:
        group, group_form, form_status, e, traceback = write_group_base(request, translation_languages, current_language, group_slug)        
        if group_slug: 
            group_temp = Group.objects.get(slug=group_slug)

        if (group_form == False and form_status == False):
            message=_("An error occurred - Please try again or contact webmaster")
            title = _("Error")
            raise e, None, traceback
      
        if group_slug:
            create_group_action = reverse('polemictweet.views.group.create_group', kwargs={'group_slug':group_slug})

        else:
            create_group_action = reverse('polemictweet.views.group.create_group')

        if form_status=='saved' or form_status=='deleted':
            return redirect('display_group', group_slug = group.slug)
            #return render_to_response('home.html', {'message': "You saved your group", 'translation_languages' : translation_languages, 'current_language' : current_language, 'group' : group}, context_instance=RequestContext(request))
        else:
            return render_to_response('create_group.html', {'group_form': group_form, 'form_status': form_status, 'create_group_action': create_group_action,
                                                                        'group_slug': group_slug, 'translation_languages' : translation_languages, 'current_language' : current_language}, context_instance=RequestContext(request))


def display_group(request, group_slug):
    current_language = get_language().split("-")[0]

    try :
        group = Group.objects.get(slug=group_slug)
    except :
        return render_to_response('home.html', {'message': "The group doesn't exist", 'current_language' : current_language}, context_instance=RequestContext(request))
   
    return render_to_response('group.html',  {'message': 'you saved your group', 'group' : group, 'current_language' : current_language}, context_instance=RequestContext(request))