from django import forms
from django.conf import settings
from django.utils.translation import ugettext_lazy as _, get_language
from models import Event, Group, Live, Content, Group, Partner
from polemictweet.utils.unique_slug import unique_slugify
from polemictweet.utils.translate_language import get_translation_languages

class ModelMultipleChoiceFieldPartner(forms.ModelMultipleChoiceField):
    def label_from_instance(self, obj):
        return "%s" % obj.name
    
class EventForm(forms.ModelForm):
    title = forms.CharField(required=True, label=_('event.title'))
    group = forms.ModelMultipleChoiceField(Group.objects.all(), widget=forms.HiddenInput, required=False)
    description = forms.CharField(widget=forms.Textarea, required=False, label=_('event.description'))
    program = forms.CharField(widget=forms.Textarea, required=False, label=_('event.program'))
    date_begin = forms.SplitDateTimeField(required = False, label=_('event.date_begin'))
    date_end = forms.SplitDateTimeField(required = False, label=_('event.date_end'))
    hashtag = forms.CharField(required=True, label=_('event.hashtag'))
    slug = forms.SlugField(required = False, widget=forms.HiddenInput, label=_('event.slug'))
    state = forms.IntegerField(required = False, widget=forms.HiddenInput, initial = 1, label=_('event.state'))
    event_image = forms.ImageField(required=False, label=_("event.event_image"))
    event_logo = forms.ImageField(required=False, label=_("event.event_logo"))
    
    def __init__(self, *args, **kwargs):
        super(EventForm, self).__init__(*args, **kwargs) 
        translation_languages = get_translation_languages()
        for lang in translation_languages:
            # generate extra fields in the number specified via extra_fields
            self.fields['title_{lang}'.format(lang=lang)] = forms.CharField(required=False, label=_('event.title_{lang}'.format(lang=lang)))
            self.fields['program_{lang}'.format(lang=lang)] = forms.CharField(widget=forms.Textarea, required=False, label=_('event.program_{lang}'.format(lang=lang)))
            self.fields['description_{lang}'.format(lang=lang)] = forms.CharField(widget=forms.Textarea, required=False, label=_('event.description_{lang}'.format(lang=lang)))
            self.fields['event_image_{lang}'.format(lang=lang)] = forms.ImageField(required=False, label=_('event.event_image_{lang}'.format(lang=lang)))
        
        
    def clean_event_image(self):
        event_image = self.cleaned_data['event_image']
                 
        if event_image and event_image.size > settings.PROFILE_IMG_MAX_SIZE:
            raise forms.ValidationError(_("Image size is limited to %s" % settings.PROFILE_IMG_MAX_SIZE))
    
        return event_image
    
    def clean_event_logo(self):
        event_logo = self.cleaned_data['event_logo']
                
        if event_logo and event_logo.size > settings.PROFILE_IMG_MAX_SIZE:
            raise forms.ValidationError(_("Image size is limited to %s" % settings.PROFILE_IMG_MAX_SIZE))
    
        return event_logo
    
    def clean_state(self):
        state = self.cleaned_data.get('state')
        if state is None:
            state = self.fields['state'].initial
        return state
        
    def clean_slug(self):
        slug = self.cleaned_data.get('slug')
        slug_str = "%s" % (self.cleaned_data.get('title'))
        if slug is None:
            slug = unique_slugify(self, slug_str)  
        return slug
    
    def clean_hashtag(self):
        # if needed, we add a "diese" to the hashtag
        hashtag = self.cleaned_data.get('hashtag')
        if '#' not in hashtag :
            hashtag = '#' + hashtag
        return hashtag
                
    def clean(self):
        super(EventForm, self).clean()
        
        default_language = settings.LANGUAGES[0][0]
        current_language = get_language().split("-")[0]
        if current_language!=default_language :                                         
            default_key_title = 'title_'+default_language
            default_key_program = 'program_'+default_language
            default_key_description = 'description_'+default_language
            default_key_event_image='event_image_'+default_language
    
            if self.cleaned_data[default_key_title] is None or self.cleaned_data[default_key_title]=='':
                self.cleaned_data[default_key_title]=self.cleaned_data.get('title')
            if self.cleaned_data[default_key_program] is None or self.cleaned_data[default_key_program]=='':
                self.cleaned_data[default_key_program]=self.cleaned_data.get('program')
            if self.cleaned_data[default_key_description] is None or self.cleaned_data[default_key_description]=='':
                self.cleaned_data[default_key_description]=self.cleaned_data.get('description')
            if self.cleaned_data[default_key_event_image] is None or self.cleaned_data[default_key_event_image]=='':
                self.cleaned_data[default_key_event_image]=self.cleaned_data.get('event_image') 
        cleaned_data = self.cleaned_data 
        return cleaned_data
    
    class Meta:
        model = Event
        exclude = ("creator_id, partners")   

class LiveAddForm(forms.ModelForm):
    provider = forms.CharField(required = False, initial ='rtmp', label=_('live.provider'))
    streamer = forms.CharField(required = False, initial='rtmp://media.iri.centrepompidou.fr/ddc-player', label=_('live.streamer'))
    file = forms.CharField(required = False, initial='livestream', label=_('live.file'))
    embed = forms.CharField( required = False, widget = forms.Textarea, label=_('live.embed'))
    type = forms.ChoiceField(widget = forms.RadioSelect(attrs={'onClick': 'toggle_type();'}), choices = ((1, "Embed"), (2, "Stream")), initial = 2,  label=_('live.type') )
    id = forms.IntegerField(required = False, widget=forms.HiddenInput, label=_("live.id") )
    
    class Meta:
        model = Live
        exclude = ("events")   
        
        
class ContentAddForm(forms.ModelForm):
    display = forms.CharField(required = False, label=_('content.display'))
    program = forms.CharField(widget = forms.Textarea, required = False, label=_('content.program'))
    url = forms.CharField(required = False, label=_('content.url'))
    id = forms.IntegerField(required = False, widget=forms.HiddenInput, label=_("content.id") )
    
    def __init__(self, *args, **kwargs):
        super(ContentAddForm, self).__init__(*args, **kwargs) 
        
        translation_languages = get_translation_languages()
  
        for lang in translation_languages:
            # generate extra fields in the different languages
            self.fields['display_{lang}'.format(lang=lang)] = forms.CharField(required=False, label=_('live.title_{lang}'.format(lang=lang)))
            self.fields['program_{lang}'.format(lang=lang)] = forms.CharField(required=False, label=_('live.program_{lang}'.format(lang=lang)))
      
    def clean(self):
        super(ContentAddForm, self).clean()
        
        default_language = settings.LANGUAGES[0][0]
        current_language = get_language().split("-")[0]
        if current_language!=default_language :       
            default_key_display = 'display_'+default_language
            default_key_program = 'program_'+default_language
    
            if self.cleaned_data[default_key_display]=='':
                self.cleaned_data[default_key_display]=self.cleaned_data.get('display')
            if self.cleaned_data[default_key_program]=='':
                self.cleaned_data[default_key_program]=self.cleaned_data.get('program')
        cleaned_data = self.cleaned_data 
        return cleaned_data 
         
    class Meta:
        model = Content
        exclude = ("events") 

class ModelMultipleChoiceFieldEvent(forms.ModelMultipleChoiceField):
    def label_from_instance(self, obj):
        return "%s" % obj.title

class GroupForm(forms.ModelForm):
    title = forms.CharField(required=True, label=_('group.title'))
    description = forms.CharField(widget=forms.Textarea, required=False, label=_('group.description'))
    image = forms.ImageField(required=False, label=_("group.image"))
    events = ModelMultipleChoiceFieldEvent(Event.objects.all(), required=False, label=_("group.events"))
    slug = forms.SlugField(required = False, widget=forms.HiddenInput, label=_('group.slug'))
    
    def __init__(self, *args, **kwargs):
        super(GroupForm, self).__init__(*args, **kwargs) 
        
        translation_languages = get_translation_languages()
        
        for lang in translation_languages:
            # generate extra fields in the different languages
            self.fields['title_{lang}'.format(lang=lang)] = forms.CharField(required=False, label=_('group.title_{lang}'.format(lang=lang)))
            self.fields['description_{lang}'.format(lang=lang)] = forms.CharField(required=False, label=_('group.description_{lang}'.format(lang=lang)))
            
    def clean_image(self):
        image = self.cleaned_data['image']
                 
        if image and image.size > settings.PROFILE_IMG_MAX_SIZE:
            raise forms.ValidationError(_("Image size is limited to %s" % settings.PROFILE_IMG_MAX_SIZE))
    
        return image
    
    def clean_slug(self):
        slug = self.cleaned_data.get('slug')
        slug_str = "%s" % (self.cleaned_data.get('title'))
        if slug is None:
            slug = unique_slugify(self, slug_str)  
        return slug
    
    def clean(self):
        super(GroupForm, self).clean()
        
        default_language = settings.LANGUAGES[0][0]
        default_key_title = 'title_'+default_language
        default_key_description = 'description_'+default_language
        current_language = get_language().split("-")[0]
        if current_language!=default_language :   
            if self.cleaned_data[default_key_title]=='':
                self.cleaned_data[default_key_title]=self.cleaned_data.get('title')
            if self.cleaned_data[default_key_description]=='':
                self.cleaned_data[default_key_description]=self.cleaned_data.get('description')
        cleaned_data = self.cleaned_data 
        return cleaned_data 
    
    class Meta:
        model = Group
        
class PartnerForm(forms.ModelForm):
    name = forms.CharField(required=True, label=_('partner.name'))
    url = forms.CharField(required=True, label=_('partner.url'))
    partner_image = forms.ImageField(required=False, label=_("partner.image"))
    
    class Meta:
        model = Partner
        