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 Event, Live, Content, Group
from polemictweet.forms import EventForm, LiveAddForm, ContentAddForm
from django.utils.translation import ugettext as _, get_language
from django.forms.formsets import formset_factory
from django.forms.models import model_to_dict
import sys
import logging

logger = logging.getLogger(__name__)

@transaction.commit_manually
def write_event_base(request, translation_languages, current_language, event_slug=None):
    event = None
    default_language = settings.LANGUAGES[0][0]
    old_groups = []
    if event_slug:
        instance_event = Event.objects.get(slug=event_slug) #@UndefinedVariable
        init_groups = instance_event.group_set.all()
        for group in init_groups :
            old_groups.append(group.id)
            
    else:
        logger.debug("No event_slug") #@UndefinedVariable
        init_groups = []
        instance_event = None

    form_status = 'none' 
    if request.method == "POST":
        logger.debug("post : "+repr(request.POST))
        try:
            if instance_event is not None:
                event_instance_val = model_to_dict(instance_event, exclude=EventForm.Meta.exclude)
            else:
                event_instance_val = {}
            event_form = EventForm(request.POST, request.FILES, instance = instance_event)
            event_valid = event_form.is_valid()
            logger.debug("write_event_base : valid form: for instance : " + repr(instance_event)) #@UndefinedVariable
            
            if event_valid : #ajouter picture_valid si image                
                if form_status != "error":    
                    event = event_form.save()
 
                    #add the event to a group :
                    #groups list :
                    group_list = []
                    for group in request.POST.getlist('groups') : 
                        group_list.append(int(group))
                    
                    #if the event already existed :
                    if event_slug :
                        # groups to remove : the one that are in the old list but not in the new list
                        to_remove = list(set(old_groups)-set(group_list))
                        for group_id in to_remove :
                            group = Group.objects.get(id=group_id)
                            group.events.remove(event)
                        
                        # groups to remove : the one that are in the new list but not in the old list
                        to_add = list(set(group_list)-set(old_groups))
                        for group_id in to_add :
                            group = Group.objects.get(id=group_id)
                            group.events.add(event)        
                        
                    else : 
                        for group_id in group_list :
                            group = Group.objects.get(id=group_id)
                            group.events.add(event)
                        
                    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
                        key_program = "program_"+language_code
                        key_event_image = "event_image_"+language_code
                        value_title = request.POST.get(key_title)
                        value_description = request.POST.get(key_description)
                        value_program = request.POST.get(key_program)
                        
                        if key_event_image in request.FILES :
                            translation_added = True
                            value_event_image = request.FILES[key_event_image]
                            if key_event_image == "event_image_fr" :
                                event.event_image_fr = value_event_image
                            elif key_event_image == "event_image_en" :
                                event.event_image_en = value_event_image
                            else :
                                event.event_image_ja = value_event_image
                                
                        if value_title and value_title!="" :
                            translation_added = True
                            if key_title == "title_fr" :
                                event.title_fr = value_title
                            elif key_title == "title_en" :
                                event.title_en = value_title
                            else :
                                event.title_ja = value_title

                        if value_description and value_description!="" :
                            translation_added = True
                            if key_description == "description_fr" :
                                event.description_fr = value_description
                            elif key_description == "description_en" :
                                event.description_en = value_description
                            else :
                                event.description_ja = value_description      
                        if value_program and value_program!="" :
                            translation_added = True
                            if key_program == "program_fr" :
                                event.program_fr = value_program
                            elif key_program == "program_en" :
                                event.program_en = value_program
                            else :
                                event.program_ja = value_program      
                    
                    # if the current language isn't the default one whici is french is this case
                    # the fields for the french will be empty which means that there is no default
                    # value when there is no translation. For exemple : if the user created an event
                    # in japanese and tries to display it in an other language, there will be nothing displayed
                    # this lines solve this problem         
                    if current_language != default_language :
                        if request.POST.get('title_fr') == '' :
                            translation_added = True
                            event.title_fr = request.POST.get('title')
                        if request.POST.get('description_fr') == '' :
                            translation_added = True
                            event.description_fr = request.POST.get('description')
                        if request.POST.get('program_fr') == '' :
                            translation_added = True   
                            event.program_fr = request.POST.get('program')
                                           
                    if translation_added :  
                        event.save()
                    form_status = 'saved'
            else:
                form_status = 'error'
        except Exception, e:
            transaction.rollback()
            __, value, traceback = sys.exc_info()
            return False, False, False, e, traceback, init_groups
 
    else:
        form_status = 'empty'
        event_form = EventForm(instance=instance_event)
               
    try:
        transaction.commit()
    except Exception, e:
        transaction.rollback()
        __, __, traceback = sys.exc_info()
        return False, False, False, e, traceback, init_groups
        
    return event, event_form, form_status, "", "", init_groups

def create_event(request, event_slug = None):
    groups = Group.objects.all()
    logger.debug("groups : "+str(groups))
    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 event", 'translation_languages' : translation_languages, 'current_language' : current_language}, context_instance=RequestContext(request))

    else:
        event, event_form, form_status, e, traceback, init_groups = write_event_base(request, translation_languages, current_language, event_slug)        
        if event_slug: 
            event_temp = Event.objects.get(slug=event_slug)

        if (event_form == False and form_status == False):
            message=_("An error occurred - Please try again or contact webmaster")
            title = _("Error")
            raise e, None, traceback
      
        if event_slug:
            create_event_action = reverse('polemictweet.views.event.create_event', kwargs={'event_slug':event_slug})

        else:
            create_event_action = reverse('polemictweet.views.event.create_event')

        if form_status=='saved' or form_status=='deleted':
            return redirect('add_live', event_slug = event.slug)
        else:
            return render_to_response('create_event.html', {'event_form': event_form, 'form_status': form_status, 'create_event_action': create_event_action,
                                                                        'event_slug': event_slug, 'translation_languages' : translation_languages, 'current_language' : current_language, 'groups' : groups, 'init_groups' : init_groups}, context_instance=RequestContext(request))



def add_live(request, event_slug) : 
    submit_action = request.REQUEST.get("submit_button", False) 
    current_language = get_language().split("-")[0]
    
    if submit_action=="close":
        all_languages = settings.LANGUAGES
        translation_languages = []
        
        for l in all_languages:
            if l[0] != current_language:
                translation_languages.append(l[0])
        return render_to_response('home.html', {'message': "You didn't add any live", 'translation_languages' : translation_languages, 'current_language' : current_language}, context_instance=RequestContext(request))
    
    else : 
        event = get_object_or_404(Event.objects, slug=event_slug)
        events = [event, ]
        init_live = event.live_set.all()
        init_value = event.live_set.all().values()
        old_live = []
        for live in init_live :
            old_live.append(live.id)
        logger.debug("addlive_init : "+str(init_live))
    
        form_status = "none"
        if request.method == "POST" :
            AddLiveFormSet = formset_factory(LiveAddForm)    
            add_live_form_set = AddLiveFormSet(request.POST)
            new_live = []
            for form in add_live_form_set : 
                form.empty_permitted = False
            if add_live_form_set.is_valid() :
                for form in add_live_form_set :
                    live = Live.create_or_change_live(type=form.cleaned_data['type'],
                                             provider=form.cleaned_data['provider'],
                                             streamer=form.cleaned_data['streamer'],
                                             file=form.cleaned_data['file'],
                                             embed=form.cleaned_data['embed'],
                                             id = form.cleaned_data['id'],
                                             events=events)
                    new_live.append(live.id)
            
                to_remove = list(set(old_live)-set(new_live))
                for live_id in to_remove :
                    live = Live.objects.get(id=live_id)
                    live.events.remove(event)
                    
                form_status = "saved"
        else:
            AddLiveFormSet = formset_factory(LiveAddForm)
            
            if len(init_live)>0 :
                add_live_form_set = AddLiveFormSet(initial = init_value)
            else :
                add_live_form_set = AddLiveFormSet()
                
            for form in add_live_form_set : 
                form.empty_permitted = False 
                
        if form_status=='saved' or form_status=='deleted':
            return redirect('add_content', event_slug = event.slug)
        else :
            add_live_event_action = reverse('polemictweet.views.event.add_live', kwargs={'event_slug':event_slug})       
            return render_to_response('add_live.html', {'add_live_form_set':add_live_form_set, 'form_status': form_status, 'events':events,
                                                            'add_live_event_action': add_live_event_action, 'current_language' : current_language }, context_instance=RequestContext(request))


def add_content(request, event_slug) :
    submit_action = request.REQUEST.get("submit_button", False) 
    current_language = get_language().split("-")[0]
    default_language = settings.LANGUAGES[0][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 didn't add any content", 'translation_languages' : translation_languages, 'current_language' : current_language}, context_instance=RequestContext(request))
    
    else :         
        event = get_object_or_404(Event.objects, slug=event_slug)
        init_content = event.content_set.all().values()
        events = [event, ]
        translation_added = False
        form_status = "none"
        if request.method == "POST" :
            AddContentFormSet = formset_factory(ContentAddForm)    
            add_content_form_set = AddContentFormSet(request.POST)
            for form in add_content_form_set : 
                form.empty_permitted = False
            if add_content_form_set.is_valid() :
                for form in add_content_form_set :
                    content = Content.create_content(display=form.cleaned_data['display'],
                                             program=form.cleaned_data['program'],
                                             url=form.cleaned_data['url'],
                                             events=events)
                                  
                    for language_code in translation_languages :
                        key_display = "display_"+language_code
                        key_program = "program_"+language_code
                        
                        value_display = request.POST.get(key_display)
                        value_program = request.POST.get(key_program)
                        
                        if value_display and value_display!="" :
                            translation_added = True
                            if key_display == "display_fr" :
                                content.display_fr = value_display
                            elif key_display == "display_en" :
                                content.display_en = value_display
                            else :
                                content.display_ja = value_display
                                 
                        if value_program and value_program!="" :
                            translation_added = True
                            if key_program == "program_fr" :
                                content.program_fr = value_program
                            elif key_program == "program_en" :
                                content.program_en = value_program
                            else :
                                content.program_ja = value_program      
                                           
                    if translation_added :  
                        content.save()
                    
                form_status = "saved"
        else:
            AddContentFormSet = formset_factory(ContentAddForm)
            #add_content_form_set = AddContentFormSet(initial = init_content)
            add_content_form_set = AddContentFormSet()
            for form in add_content_form_set : 
                form.empty_permitted = False 
                
        if form_status=='saved' or form_status=='deleted':
            return redirect('display_event', event_slug = event.slug)
        else :
            add_content_event_action = reverse('polemictweet.views.event.add_content', kwargs={'event_slug':event_slug})       
            return render_to_response('add_content.html', {'add_content_form_set':add_content_form_set, 'form_status': form_status, 'events':events,
                                                            'add_content_event_action': add_content_event_action, 'current_language' : current_language, 'translation_languages' : translation_languages }, context_instance=RequestContext(request))

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

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