from django import forms

from django.conf import settings
from .models import *
from django.contrib.auth.forms import UserCreationForm
from django_file_form.forms import UploadedFileField, FileFormMixin, CharField, MultipleUploadedFileField
from django.contrib.auth.models import User
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Field, Fieldset, Div, Row, Column, HTML, ButtonHolder, Submit
from crispy_forms.bootstrap import InlineField
from django.forms.models import inlineformset_factory
from django.forms import formset_factory
from django import forms
from captcha.fields import CaptchaField
from django.core.files import File
from marktplatz.widgets import *


class VoteForm(forms.Form):
    aestethic = forms.DecimalField(label='Aesthetic Qualities', max_value=10,  decimal_places =1,required=False)
    innovation = forms.DecimalField(label='Innovative Elements',max_value=10, decimal_places =1,required=False)
    technical = forms.DecimalField(label='Technical Qualities', max_value=10, decimal_places =1,required=False)
    integration = forms.DecimalField(label='Integration of diffrent Components',
                                     max_value=10, decimal_places=1,
                                     help_text='e.g. architecture,display and content',required=False)
    comment = forms.CharField(max_length=300, widget=forms.Textarea(), help_text = 'You can leave your written comment here!',required=False)

    def clean(self):
        cleaned_data = super(VoteForm, self).clean()
        aestethic =cleaned_data.get('aestethic')
        innovation = cleaned_data.get('innovation')
        technical = cleaned_data.get('technical')
        integration = cleaned_data.get('integration')
        comment = cleaned_data.get('comment')

    #initial can be specified with old value in db maybe

class searchAgentForm(forms.ModelForm):

    class Meta:
        model = SearchAgent
        fields = '__all__'
        # fields = ('first_name','last_name','adress','postcode','city','country', 'email','phonenumber','alternate_phonenumber','skype_name','website', 'terms')

class RegisterForm(forms.ModelForm):
    terms = forms.BooleanField(required=True,  label= ('I accept and have read the <a href="https://www.mediaarchitecture.org/privacy-policy/">Privacy Policy.</a>'))

    class Meta:
        model = Contact
        fields = ('first_name','last_name','adress','postcode','city','country',
                  'email','phonenumber','alternate_phonenumber','skype_name','website', 'terms')

class SignUpForm(UserCreationForm):
    captcha = CaptchaField( generator='captcha.helpers.math_challenge' )

    class Meta:
        model = User
        fields = ('username', 'password1', 'password2')



def extend_help_text( help_text, myList ):
    extended_text = help_text
    extended_text += "  z.B. "
    for x in myList:
        extended_text += x[1] + ", "
    extended_text = extended_text[:-2]
    extended_text += "."
    return extended_text

class SubmissionForm(forms.ModelForm):

    terms = forms.BooleanField(required=True,  label= ('I accept and have read the Terms of Participation.'))

    class Meta:
        model = Wohnprojekt
        fields = (
        # 'title','country','city','year','owner','teaser_txt','header','category', 'description_txt',
         'terms',
        'name','claim','beschreibung','learning','gruendungsjahr','betriebgenommen','status','adresse','website','email','frei','kfrei', 'mitmachen','rechtsform','ort','orga',
         'eigentum', 'inseratstext', 'altneu', 'schwerpunkt', 'wohnbaufoerderung', 'artmodell', 'bautraeger', 'aerwachsene', 'akinder', 'awohnungen', 'wohnflaeche', 'gewerbeflaechen', 'gemeinschaftsflaeche', 'sonstige_flaechen', 'kflaechen', 'gemeinschaftr', 'kgemeinschaftr', 'sonderwohnformen', 'raumangebot', 'kraumangebot', 'parbeiten', 'karbeiten', 'bauweise', 'zielgruppen', 'gprojekte', 'oekologie', 'freiraumangebote', 'gaestwohnungen',
         )


    def __init__(self,*args, **kwargs):
       super(SubmissionForm, self).__init__(*args, **kwargs)

       #
       #
       self.fields['orga'].widget        = ListTextWidget(data_list=Product.ORGANIZATION,  name='orga_list')
       self.fields['rechtsform'].widget  = ListTextWidget(data_list=Product.RECHTSFORM,  name='rechtsform_list')
       self.fields['artmodell'].widget   = ListTextWidget(data_list=Wohnprojekt.ARTMODELL,  name='artmodell_list')
       self.fields['bautraeger'].widget  = ListTextWidget(data_list=Wohnprojekt.BAUTRAEGER,  name='bautraeger_list')
       self.fields['bauweise'].widget    = ListTextWidget(data_list=Wohnprojekt.BAUWEISE,  name='bauweise_list')
       self.fields['zielgruppen'].widget = ListTextWidget(data_list=Wohnprojekt.ZIELGRUPPEN,  name='zielgruppen_list')
       self.fields['gprojekte'].widget   = ListTextWidget(data_list=Wohnprojekt.GPROJEKTE,  name='gprojekte_list')
       #
       #
       self.fields['orga'].help_text        = extend_help_text (self.fields['orga'].help_text, Product.ORGANIZATION)
       self.fields['rechtsform'].help_text  = extend_help_text (self.fields['rechtsform'].help_text, Product.RECHTSFORM)
       self.fields['bauweise'].help_text    = extend_help_text (self.fields['bauweise'].help_text, Wohnprojekt.BAUWEISE)
       self.fields['zielgruppen'].help_text = extend_help_text (self.fields['zielgruppen'].help_text, Wohnprojekt.ZIELGRUPPEN)
       self.fields['gprojekte'].help_text   = extend_help_text (self.fields['gprojekte'].help_text, Wohnprojekt.GPROJEKTE)
       #
       #

       self.helper = FormHelper()
       self.helper.form_tag = False
       self.helper.layout = Layout(
           Fieldset(
               ('Über dein Projekt'),

               'name','claim','beschreibung','learning','status',

              Div(
                  Div('adresse',  css_class='col-sm-6 col-6'),
                  Div('ort', css_class='col-sm-6 col-6'),
                  css_class='form-row  row'),

              Div(
                  Div('frei',  css_class='col-sm-6 col-6'),
                  Div('kfrei', css_class='col-sm-6 col-6'),
                  css_class='form-row  row'),

              'mitmachen','rechtsform','orga',

              Div(
                  Div('website',  css_class='col-sm-6 col-6'),
                  Div('email', css_class='col-sm-6 col-6'),
                  css_class='form-row  row'),


              Div(
                  Div('gruendungsjahr',  css_class='col-sm-6 col-6'),
                  Div('betriebgenommen', css_class='col-sm-6 col-6'),
                  css_class='form-row  row'),

             'eigentum', 'inseratstext', 'altneu', 'schwerpunkt', 'wohnbaufoerderung', 'artmodell', 'bautraeger',

              Div(
                  Div('aerwachsene',  css_class='col-sm-6 col-6'),
                  Div('akinder', css_class='col-sm-6 col-6'),
                  css_class='form-row  row'),

             'awohnungen',

              Div(
                  Div('wohnflaeche',  css_class='col-sm-3 col-3'),
                  Div('gewerbeflaechen', css_class='col-sm-3 col-3'),
                  Div('gemeinschaftsflaeche', css_class='col-sm-3 col-3'),
                  Div('sonstige_flaechen', css_class='col-sm-3 col-3'),
                  css_class='form-row  row'),
             'kflaechen', 'gemeinschaftr', 'kgemeinschaftr', 'raumangebot', 'kraumangebot', 'sonderwohnformen', 'parbeiten', 'karbeiten', 'bauweise', 'zielgruppen', 'gprojekte', 'oekologie', 'freiraumangebote', 'gaestwohnungen',

           )
       )




class CreditForm(forms.ModelForm):
    class Meta:
        model = Credit
        fields = ('owner','architecture','concept','structural_engeneering','facade_design',
                    'face_construction','kinetic_design','light_design','tecnical_layout',
                    'display_content','light_hardware','lightning_software','product_coordination',
                    'membrane_skin','interaction_design','sponsor','module_elems')

    def __init__(self, *args, **kwargs):
        super(CreditForm, self).__init__(*args, **kwargs)

        self.fields['owner'].help_text = ('<i>e.g. Cardinal Group</i>')
        self.fields['architecture'].help_text = ('<i>e.g. Domenico Torrone and Partners</i>')
        self.fields['concept'].help_text = ('<i>e.g. Domenico Torrone and Partners</i>')
        self.fields['structural_engeneering'].help_text = ('<i>e.g. Osap Inc., Hongkong</i>')
        self.fields['facade_design'].help_text = ('<i>e.g. Mega Facades Inc, Beijing</i>')
        self.fields['face_construction'].help_text = ('<i>e.g. None</i>')
        self.fields['kinetic_design'].help_text = ('<i>e.g. Domenico Torrone and Osap, Hongkong</i>')
        self.fields['light_design'].help_text = ('<i>e.g. Domenico Torrone and Osap, Hongkong</i>')
        self.fields['tecnical_layout'].help_text = ('<i>e.g. Modul Labs, Berlin</i>')
        self.fields['display_content'].help_text = ('<i>e.g. Domenico Torrone;reality check, Munich;</i>')
        self.fields['light_hardware'].help_text = ('<i>e.g. Modul Labs, Berlin</i>')
        self.fields['lightning_software'].help_text = ('<i>e.g. Dimma DMX by Eflux</i>')
        self.fields['product_coordination'].help_text = ('<i>e.g. Domenico Torrone and Partners</i>')
        self.fields['membrane_skin'].help_text = ('<i>e.g. none</i>')
        self.fields['interaction_design'].help_text = ('<i>e.g. pixeldings, Toronto</i>')
        self.fields['sponsor'].help_text = ('<i>e.g. none</i>')
        self.fields['module_elems'].help_text = ('<i>e.g. Maxi PIX 12 by Eflux</i>')

        self.fields['owner'].max_length = 100
        self.fields['architecture'].max_length = 100
        self.fields['concept'].max_length = 100
        self.fields['structural_engeneering'].max_length = 100
        self.fields['facade_design'].max_length = 100
        self.fields['face_construction'].max_length = 100
        self.fields['kinetic_design'].max_length = 100
        self.fields['light_design'].max_length = 100
        self.fields['tecnical_layout'].max_length = 100
        self.fields['display_content'].max_length = 100
        self.fields['light_hardware'].max_length = 100
        self.fields['lightning_software'].max_length = 100
        self.fields['product_coordination'].max_length = 100
        self.fields['membrane_skin'].max_length = 100
        self.fields['interaction_design'].max_length = 100
        self.fields['sponsor'].max_length = 100
        self.fields['module_elems'].max_length = 100

        self.helper = FormHelper()
        self.helper.field_class = 'form_border'
        self.helper.form_tag = False
        self.helper.layout = Layout(
            Fieldset(
                ('Credits'),
                 Div( Div('owner',css_class='form-group col-md-5 mb-0'),  Div('architecture',css_class='form-group col-md-5 mb-0'), css_class='form-row'),
                 Div( Div('concept',css_class='form-group col-md-5 mb-0'),  Div('structural_engeneering',css_class='form-group col-md-5 mb-0'), css_class='form-row'),
                 Div( Div('facade_design',css_class='form-group col-md-5 mb-0'), Div('face_construction',css_class='form-group col-md-5 mb-0'),  css_class='form-row'),
                 Div( Div('kinetic_design',css_class='form-group col-md-5 mb-0'),  Div('light_design',css_class='form-group col-md-5 mb-0'), css_class='form-row'),
                 Div( Div('tecnical_layout',css_class='form-group col-md-5 mb-0'), Div('display_content',css_class='form-group col-md-5 mb-0'), css_class='form-row'),
                 Div( Div('light_hardware',css_class='form-group col-md-5 mb-0'),  Div('lightning_software',css_class='form-group col-md-5 mb-0'), css_class='form-row'),
                 Div( Div('product_coordination',css_class='form-group col-md-5 mb-0'),  Div('membrane_skin',css_class='form-group col-md-5 mb-0'), css_class='form-row'),
                 Div( Div('interaction_design',css_class='form-group col-md-5 mb-0'),  Div('sponsor',css_class='form-group col-md-5 mb-0'),  css_class='form-row'),
                Div( Div( 'module_elems',css_class='form-group col-md-5 mb-0'),  css_class='form-row')
            ))




class DescriptionForm(forms.ModelForm):
    class Meta:
        model = Description
        fields =('facade','light_creation','resolution','pixel_distance','luminance','urban_situation','description_showreel')

    def __init__(self, *args, **kwargs):
        super(DescriptionForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.layout = Layout(
            Fieldset(
                ('Concept Descriptions'),
                Div(Div('des_concept', css_class='form-group col-md-12 mb-0'), css_class='form-row'),
                Div(Div('des_scenario', css_class='form-group col-md-6 mb-0'),
                    Div('des_approach', css_class='form-group col-md-6 mb-0'), css_class='form-row'),
                Div(Div('des_tech', css_class='form-group col-md-6 mb-0'),
                    Div('des_visual', css_class='form-group col-md-6 mb-0'), css_class='form-row'),
               ))

class InteractionForm(forms.ModelForm):
    class Meta:
        model = Interaction
        fields = ('communtity','host','legal_form','issues','impact','tools','tools_used','next_steps')

    def __init__(self, *args, **kwargs):
        super(InteractionForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.layout = Layout(
            Fieldset(
                ('Community Ascpects - not mandatory'),
                Div(Div('communtity', css_class='form-group col-md-6 mb-0'),
                    Div('issues', css_class='form-group col-md-6 mb-0'), css_class='form-row'),
                Div(Div('legal_form', css_class='form-group col-md-6 mb-0'),
                    Div('host', css_class='form-group col-md-6 mb-0'), css_class='form-row'),
                Div(Div('impact', css_class='form-group col-md-6 mb-0'),
                    Div('tools', css_class='form-group col-md-6 mb-0'), css_class='form-row'),
                Div(Div('tools_used', css_class='form-group col-md-6 mb-0'),
                    Div('next_steps', css_class='form-group col-md-6 mb-0'), css_class='form-row'),
            ))

class LinkForm(forms.ModelForm):
    class Meta:
        model = Link
        fields = ('link_description','link')

    #def __init__(self, *args, **kwargs):
    #    super(LinkForm, self).__init__(*args, **kwargs)
    #    self.helper = FormHelper()
    #    self.helper.field_class = 'form_border'
    #    self.helper.form_tag = False
    #    self.helper.layout = Layout(
    #        Fieldset(
    #            Div(Div('link_description', css_class='form-group col-md-5 mb-0'),
    #            Div('link', css_class='form-group col-md-5 mb-0'),
    #                css_class='form-row')
    #        ))


LinkFormSet = inlineformset_factory(Product,Link, fields = ['link_description','link'], form=LinkForm, extra=3, can_delete=False)


class FormsetHelper(FormHelper):
    def __init__(self,*args, **kwargs):
        super(FormsetHelper, self).__init__(*args, **kwargs)
        #self.form_method = 'post'
        self.form_tag = False
        #self.render_hidden_fields = True
        #self.render_required_fields = True
        self.layout = Layout(
            Fieldset(
                (''),
                Div(
                    Div('link_description', css_class='form-group col-md-4 mb-0'),
                    Div('link', css_class='form-group col-md-6 mb-0')
                    , css_class='form-row')
            ))


class MediaForm(FileFormMixin, forms.Form):
    image = UploadedFileField()
    name_for = CharField()
    copyright = CharField()
    #prefix = 'upload'


    def __init__(self, *args, **kwargs):
        super(MediaForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.fields['name_for'].label = 'Caption'
        self.fields['copyright'].label = 'Copyright of'
        self.fields['image'].label = 'Image or Video'
        self.fields['image'].help_text = 'Please upload Images in PNG or JPEG format. Upload Video in MP4 format.'
        self.layout = Layout(
            Fieldset(
                (''),
                Div(
                    Div('name_for', css_class='form-group col-md-6 mb-0'),
                    Div('copyright', css_class='form-group col-md-4 mb-0')
                    , css_class='form-row'),
                Div(
                    Div('image', css_class='form-group col-md-6 mb-0'),
                    css_class='form-row'),
            ))


   #def is_valid(self):
   #    super(MediaForm,self).is_valid()
   #    return True


   #def clean(self):
   #    cleaned_data = super(MediaForm,self).clean()

   #    #test for valid formats
   #    #if cleaned_data['image']
   #    #    raise ValidationError('Title field is required')
   #    return cleaned_data


   #def save(self, Product_pk):
   #    self.clean()
   #    media = Media()
   #    print('hallo')
   #    media.Product= Product_pk
   #    media.image=self.cleaned_data['image']
   #    media.name_for=self.cleaned_data['name_for']
   #    media.copyright =self.cleaned_data['copyright']
   #    media.Product= Product_pk
   #    media.save()

   ##    self.delete_temporary_files()


class MediaForm_test(FileFormMixin, forms.Form):
    image = UploadedFileField()
    name_for = CharField()
    copyright = CharField()

    def __init__(self, *args, **kwargs):
        super(MediaForm_test, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_tag = False


class MediaForm1(FileFormMixin, forms.Form):
    image = MultipleUploadedFileField()
    name_for = CharField()
    copyright = CharField()

    def __init__(self, *args, **kwargs):
        super(MediaForm1, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_tag = False


class MediaForm2(FileFormMixin,forms.Form):
    image = UploadedFileField()
    name_for = CharField()
    copyright = CharField()

    def __init__(self, *args, **kwargs):
        super(MediaForm2, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_tag = False


MediaFormSet = formset_factory(MediaForm_test, extra=3)


class MediaFormsetHelper(FormHelper):

    def __init__(self,*args, **kwargs):
        super(MediaFormsetHelper, self).__init__(*args, **kwargs)
        self.form_tag = False
        self.layout = Layout(
            Fieldset(
                (''),
                Div(
                    Div('name_for', css_class='form-group col-md-6 mb-0'),
                    Div('copyright', css_class='form-group col-md-4 mb-0')
                    , css_class='form-row'),
                Div(
                    Div('image', css_class='form-group col-md-6 mb-0'),
                    css_class='form-row'),
            ))


class VideoForm(forms.ModelForm):
    class Meta:
        model = Video
        fields = ('name_for','copyright','image')
