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, Partner, Organisator
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
from polemictweet.utils.translate_language import get_translation_languages
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
    old_groups = []
    old_partners = []
    old_partners_id = []
    old_organisators = []
    old_organisators_id = []
    
    
    if event_slug:
        instance_event = Event.objects.get(slug=event_slug) #@UndefinedVariable
        init_groups = instance_event.group_set.all()
        init_partners = Organisator.objects.filter(event=instance_event, orga=False)
        init_organisators = Organisator.objects.filter(event=instance_event, orga=True)
        
        logger.debug("init_partners : "+str(init_partners))
        for group in init_groups :
            old_groups.append(group.id)
        
        for partner in init_partners : 
            old_partners.append(partner.partner)
            logger.debug('name '+str(partner.partner.name))
            old_partners_id.append(partner.partner.id)

        for organisator in init_organisators : 
            old_organisators.append(organisator.partner)
            old_organisators_id.append(organisator.partner.id)
            logger.debug('name '+str(organisator.partner.name))
    
            
    else:
        logger.debug("No event_slug") #@UndefinedVariable
        init_groups = []
        instance_event = None

    form_status = 'none' 
    if request.method == "POST":
        logger.debug("post : "+str(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 = []
                    partner_list = []
                    organisator_list = []
                    for group in request.POST.getlist('groups') : 
                        group_list.append(int(group))
                        
                    for partner in request.POST.getlist('partners') : 
                        partner_list.append(int(partner))
                    
                    for organisator in request.POST.getlist('organisators') : 
                        organisator_list.append(int(organisator))
                    
                    #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
                        group_to_remove = list(set(old_groups)-set(group_list))
                        group_to_add = list(set(group_list)-set(old_groups))

                        partner_to_remove = list(set(old_partners_id)-set(partner_list))
                        partner_to_add = list(set(partner_list)-set(old_partners_id))
                        
                        organisator_to_remove = list(set(old_organisators_id)-set(organisator_list))
                        organisator_to_add = list(set(organisator_list)-set(old_organisators_id))
                        
                        # groups to remove : the one that are in the new list but not in the old list
                        for group_id in group_to_remove :
                            group = Group.objects.get(id=group_id)
                            group.events.remove(event)
                        
                        for group_id in group_to_add :
                            group = Group.objects.get(id=group_id)
                            group.events.add(event)   
                                 
                        for partner_id in partner_to_remove :
                            partner = Partner.objects.get(id=partner_id)
                            Organisator.objects.filter(event=event, partner = partner).delete()  
                        
                        for partner_id in partner_to_add :
                            partner = Partner.objects.get(id=partner_id)
                            Organisator.objects.create(partner = partner, event = event, orga = False)     
                        
                        for organisator_id in organisator_to_remove :
                            organisator = Partner.objects.get(id=organisator_id)
                            Organisator.objects.filter(event=event, partner = organisator).delete()
              
                        
                        for organisator_id in organisator_to_add :
                            organisator = Partner.objects.get(id=organisator_id)
                            Organisator.objects.create(partner = organisator, event = event, orga = True)    
                        
                    else : 
                        for group_id in group_list :
                            group = Group.objects.get(id=group_id)
                            group.events.add(event)
                        
                        for partner_id in partner_list :
                            partner = Partner.objects.get(id=partner_id)
                            Organisator.objects.create(partner = partner, event = event, orga = False)
                        
                        for organisator_id in organisator_list :
                            organisator = Partner.objects.get(id=organisator_id)
                            Organisator.objects.create(partner = organisator, event = event, orga = True)
                        
                    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, old_partners, old_organisators
 
    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, old_partners, old_organisators
        
    return event, event_form, form_status, "", "", init_groups, old_partners, old_organisators

def create_event(request, event_slug = None):
    groups = Group.objects.all()
    partners = Partner.objects.all()
    logger.debug("partner : "+str(partners))
    submit_action = request.REQUEST.get("submit_button", False) 
    current_language = get_language().split("-")[0]
    translation_languages = get_translation_languages()

    
    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, old_partners, old_organisators = 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, 'partners' : partners, 'old_partners' : old_partners, 'old_organisators' : old_organisators,
                                                                        '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":
        translation_languages = get_translation_languages()

        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)
    
        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]
    translation_languages = get_translation_languages()
            
    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)
        events = [event, ]
        init_content = event.content_set.all()
        init_value = init_content.values()
        old_content = []
        
        for content in init_content :
            old_content.append(content.id)
        
        form_status = "none"
        new_content = []
        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_or_change_content(data=form.cleaned_data,
                                             events=events)
                    new_content.append(content.id)
                
                to_remove = list(set(old_content)-set(new_content))
                for content_id in to_remove :
                    content = Content.objects.get(id=content_id)
                    content.events.remove(event)
                    
                form_status = "saved"
        else:
            AddContentFormSet = formset_factory(ContentAddForm)
            #add_content_form_set = AddContentFormSet(initial = init_content)
            if len(init_content)>0 :
                add_content_form_set = AddContentFormSet(initial = init_value)
            else :
                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))