from django import forms

from django.conf import settings
from django.core.files import File
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 django.urls import reverse, reverse_lazy
from django.forms import formset_factory
from django.forms.widgets import HiddenInput
from django.forms.models import inlineformset_factory
# from django.views.generic.edit.FormMixin
# from crispy_forms.layout.buttons import Submit, InputButton

from crispy_forms.layout import Layout, Field, Fieldset, Div, Row, Column, HTML, ButtonHolder, Submit
from crispy_forms.bootstrap import InlineField
from crispy_forms.helper import FormHelper
from captcha.fields import CaptchaField
from newsletter.forms import *

from marktplatz.widgets import *
from .models import *
from .urls import *

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 GeneralFields(forms.Form):
    terms = forms.BooleanField(required=True, )

    def __init__(self, *args, **kwargs):
        super(GeneralFields, self).__init__(*args, **kwargs)
        drurl = reverse_lazy( 'pages-generic', kwargs=  { 'page': 'DATENSCHUTZRICHTLINIE' } )
        tmurl = reverse_lazy( 'pages-generic', kwargs=  { 'page': 'TEILNAHME' } )
        self.fields ['terms'].label = 'Ich akzeptiere die <a  target="_blank" href="{}"> Datenschutzrichtlinie</a> sowie die  <a  target="_blank" href="{}"> Teilnahmebedingungen</a> und habe sie gelesen.'.format(drurl, tmurl)




class textSearchForm(forms.Form):

    mywidget = forms.TextInput(  attrs={'onfocus': "this.value=''", 'class' : "border-thin"}  )
    searchText = forms.CharField ( label='', widget = mywidget, max_length = 2048, min_length=3, empty_value="Suche...", initial='Suche...' )

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

           Div(
               Div('searchText',  css_class='col-sm-6 col-6'),
               Div(
                   ButtonHolder(
                       Submit('submit', 'Suche', css_class='border-thin mybtn')
                   ),
               css_class='col-sm-6 col-6'),
               css_class='form-row row mab-search-bar'),
           )


class searchAgentForm(forms.ModelForm):


    class Meta:
        model = SearchAgent
        fields = ('ort', 'email')

    agent_layout = Layout(
        Fieldset(
            ('Suchagent'),
            'ort',
        ),
    )

    # def __init__(self, *args, **kwargs):
    #     super().__init__(*args, **kwargs)
    #     self.fields ['ort'].label = 'Ich akzeptiere die <a href="{}"> Datenschutzrichtlinie</a> sowie die  <a href="{}"> Teilnahmebedingungen</a> und habe sie gelesen.'.format(drurl, tmurl)


class AgentNewslwtterForm( searchAgentForm, GeneralFields):

    email_field = forms.EmailField( label = 'Email', required=True, max_length=254 )
    subscribe = forms.BooleanField( label = 'Newsletter abonnieren', help_text='', required = False )
    captcha = CaptchaField( label = 'Bitte lösen Sie die Gleichung', generator='captcha.helpers.math_challenge' )

    def __init__(self, *args, **kwargs):
        super(searchAgentForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.attrs = {  'enctype' : "multipart/form-data" }
        self.helper.form_action = reverse('agent-newsletter-create', kwargs={'newsletter_slug': "test_news"}    )

        self.helper.layout = Layout(
            self.agent_layout,
           'email_field',
           'subscribe',
           'terms',
           'captcha',
           ButtonHolder(
               Submit('submit', 'Anmelden', css_class='border-thin border-dark mybtn')
           ),
       )



class RegisterForm(forms.ModelForm, GeneralFields):

    class Meta:
        model = Contact
        fields = ('first_name','last_name','email','adress','postcode','city','country',
                  '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')

class ProductForm(forms.ModelForm, GeneralFields):

    # terms = forms.BooleanField(required=True,  label= ('Ich habe die Teilnahmebedingungen gelesen und akzeptiert.'))
    product_fields = ( 'terms', 'name','claim','beschreibung','learning','gruendungsjahr','betriebgenommen','status','adresse','website','email','frei','kfrei','ort','rechtsform','orga','mitmachen','edit','public', )
    product_layout = Layout(
        Fieldset(
            ('Über dein Projekt'),
            'name','claim','beschreibung',
            Div(
                Div('frei',  css_class='col-sm-6 col-6 '),
                Div('kfrei', css_class='col-sm-6 col-6 ' ),
            css_class='form-row row mab-field-highlight'),
            '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'),
           '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'),
          'edit','public', 'mitmachen',
        ),
    )

    class Meta:
        model = Product
        fields = (
         'terms',
        'name','claim','beschreibung','learning','gruendungsjahr','betriebgenommen','status','adresse','website','email','frei','kfrei', 'mitmachen','rechtsform','ort','orga',
         )

    def __init__(self,*args, **kwargs):
       super(ProductForm, 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['edit'].widget  = HiddenInput()
       self.fields['public'].widget  = HiddenInput()
       #
       # extend_help_text
       #
       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.helper = FormHelper()
       self.helper.form_tag = False



class WohnprojektForm(ProductForm):

    terms = forms.BooleanField(required=True,  label= ('Ich habe die Teilnahmebedingungen gelesen und akzeptiert.'))


    class Meta:
        model = Wohnprojekt
        fields = ProductForm.product_fields + (
         '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(WohnprojektForm, self).__init__(*args, **kwargs)

       #
       #
       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['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.fields['frei'].label   = "Wohnung Frei"



       self.helper = FormHelper()
       self.helper.form_tag = False
       self.helper.layout = Layout(
            self.product_layout,

           Fieldset(
             'Wohnprojekt',
             'eigentum',  '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',
             'gaestwohnungen',
             Fieldset ( 'Flächen',
                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',
             ),
              Div(
                Div('gemeinschaftr',  css_class='col-sm-6 col-6'),
                Div('raumangebot', css_class='col-sm-6 col-6'),
                Div('kgemeinschaftr',  css_class='col-sm-6 col-6'),
                Div('kraumangebot', css_class='col-sm-6 col-6'),
              css_class='form-row  row'),
              Div('inseratstext', css_class = "mab-field-highlight"),
              'sonderwohnformen',

              Div(
                  Div('parbeiten',  css_class='col-sm-6 col-6'),
                  Div('karbeiten', css_class='col-sm-6 col-6'),
                  css_class='form-row  row'),

               'bauweise', 'zielgruppen', 'gprojekte', 'oekologie', 'freiraumangebote',

           )
       )









# 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 = forms.CharField()
    copyright = forms.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 = 'Bildbeschriftung'
        self.fields['copyright'].label = 'Urheberrechte'
        self.fields['image'].label = 'Bild oder Video'
        self.fields['image'].help_text = 'Bitte laden Sie Bilder im PNG- oder JPEG-Format hoch. Laden Sie Videos im MP4-Format hoch.'
        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 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')
