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 *
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 *
from crispy_forms.bootstrap import InlineField, InlineCheckboxes
from crispy_forms.helper import FormHelper
from captcha.fields import CaptchaField
from tinymce.widgets import TinyMCE
from newsletter.forms import *
from newsletter.models 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-4 col-4'),
               Div(
                   ButtonHolder(
                       Submit('submit', 'Suche', css_class='border-thin mybtn')
                   ),
               css_class='col-sm-2 col-2'),
               css_class='form-row row mab-search-bar'),

           )


class searchAgentForm(forms.ModelForm):

    agent_layout = Layout()

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

    def __init__(self,*args, **kwargs):
        super().__init__(*args, **kwargs)
        # self.fields['ort'].widget        = CheckboxSelectMultiple( attrs= { 'style' : "min-height: 250px;"} )
        self.agent_layout = Layout(
            Fieldset(
                ('Suchagent einrichten'),
                # 'ort',

               Div(

                   Div(

                       HTML("""
                       <br>
                       <button onclick=" ganz_wien()" class="btn btn-primary border-thin border-dark mybtn">Ganz Wien</button>
                       <script>
                        function ganz_wien(){
                          $(".checkbox-ort .custom-control-label:contains('Wien')").each(function() {
                           $this = $(this);
                           var selector = "#" + $this.attr('for')  ;
                           $( selector ).prop('checked', true);
                        });
                        }
                       </script>
                       <br><br>
                       """),

                   css_class='col-sm-6 col-6'),

              css_class='form-row  row'),


               Div(

                   Div(

                   InlineCheckboxes('ort'),
                   css_class='col-sm-8 col-8 checkbox-ort'

                   ),

               css_class='form-row  row'),





            ),
        )





class AgentNewslwtterForm( searchAgentForm, GeneralFields):

    email_field = forms.EmailField( label = 'Email', help_text="Du kannst den Suchagenten und den Newsletter jederzeit abbestellen - über einen Link in den Mails.", 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)
        super(AgentNewslwtterForm, 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': "gemeinschaffen-newsletter"}    )

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


class NewsletterForm(SubscribeRequestForm, GeneralFields):

    class Meta:
        model = SubscribeRequestForm.Meta.model
        fields = SubscribeRequestForm.Meta.fields + (
         'terms', )

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


       self.helper = FormHelper()
       self.helper.form_tag = False

       self.layout = Layout(
               Fieldset(
                   ('Anmelden'),
                   'name_field',
                   'email_field',
                   'terms',
                  Div(
                      ButtonHolder(
                          Submit('submit', 'Anmelden', css_class='border-thin mybtn')
                      ),
                  ),
                  Div(HTML("&nbsp;") ),
               ),
           )
       self.helper.layout = self.layout


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')

#
# CREATE
#


class ProductForm(forms.ModelForm, GeneralFields):

    class Meta:
        model = Product
        type = 'BASE'
        fields = ( 'terms', 'name','claim','beschreibung','learning','gruendungsjahr','betriebgenommen','status',
        'adresse', 'adresse_zusatz', 'plz', 'website','email','frei','kfrei','ort','rechtsform','orga','realitylab',
        'edit','public','type', )


    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['beschreibung'].widget  = TinyMCE(attrs={'cols': 80, 'rows': 30})
       self.fields['learning'].widget  = TinyMCE(attrs={'cols': 80, 'rows': 30})
       self.fields['edit'].widget  = HiddenInput()
       self.fields['public'].widget  = HiddenInput()
       self.fields['type'].widget  = HiddenInput()
       self.fields['type'].initial  = 'BASE'
       #
       # 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)


       #
       # FORM HELPER
       #

       if 'instance' in kwargs:
           if kwargs['instance'] is not None:
               self.redirect_to_pics    = reverse_lazy( 'projekt-bearbeiten-submit-pics', kwargs=  { 'type': self.Meta.type, 'pk': kwargs['instance'].id     }  )
               self.redirect_to_publish = reverse_lazy( 'projekt-bearbeiten-publish',     kwargs=  { 'type': self.Meta.type, 'pk': kwargs['instance'].id  }  )
           else:
               self.redirect_to_pics    = reverse_lazy( 'neues-projekt-submit-pics',  kwargs =  { 'type': self.Meta.type }  )
               self.redirect_to_publish = reverse_lazy( 'neues-projekt-publish',      kwargs =  { 'type': self.Meta.type }  )



       self.helper = FormHelper(  )
       self.helper.attrs = {'id': 'upload_mab', 'enctype': 'multipart/form-dat' }
       # self.helper.form_tag = True

       self.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('adresse_zusatz', css_class='col-sm-6 col-6'),
                      css_class='form-row  row'),
                  Div(
                      Div('plz',  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', 'realitylab', 'type',
               ),
           )

       self.submit_layout = Layout(
        'terms',

        HTML("<br>"),

        Div(
          Div(
              ButtonHolder(
              Submit('submit', 'Speichern',
              css_class='border-thin mybtn')
              ),
          css_class='col-sm-4 col-4'),
          Div(
            ButtonHolder(
              Submit('submit', 'Speichern & Bilder hochladen',
                onclick='this.form.action="{}";'.format(  self.redirect_to_pics  ),
                css_class='border-thin mybtn')
          ),
          css_class='col-sm-4 col-4'),
          Div(
            ButtonHolder(
                Submit('submit', 'Speichern und Freischaltung Anfragen',
                  onclick='this.form.action="{}";'.format(  self.redirect_to_publish  ),
                  css_class='border-thin mybtn'
                  ),
             HTML("<br><p>Dein Projekt ist noch nicht für jede Person sichtbar, damit wir dein Projekt freischalten, klicke auf diesen Button.</p>")
            ),
            css_class='col-sm-4 col-4'),
          css_class='form-row  row'),
        )


       self.helper.layout = Layout(
        self.product_layout,
        self.submit_layout,
        )


class MobilitaetsForm(ProductForm):

    class Meta():
        model =  MobilitaetsProjekt
        type = 'MOBI'
        fields = ProductForm.Meta.fields + ( )

    def __init__(self,*args, **kwargs):
        super(MobilitaetsForm, self).__init__(*args, **kwargs)
        self.fields['type'].initial  = 'MOBI'


class ErnaehrungsForm(ProductForm):

    class Meta():
        model =  ErnaehrungsProjekt
        type = 'ERNA'
        fields = ProductForm.Meta.fields + ( )

    def __init__(self,*args, **kwargs):
        super(ErnaehrungsForm, self).__init__(*args, **kwargs)
        self.fields['type'].initial  = 'ERNA'

class EnergyForm(ProductForm):

    class Meta():
        model =  EnergyProjekt
        type = 'ENER'
        fields = ProductForm.Meta.fields + ( )

    def __init__(self,*args, **kwargs):
        super(EnergyForm, self).__init__(*args, **kwargs)
        self.fields['type'].initial  = 'ENER'


class WohnprojektForm(ProductForm):

    class Meta:
        model = Wohnprojekt
        type = 'WOHN'
        fields = ProductForm.Meta.fields + (
         'eigentum', 'inseratstext', 'altneu', 'schwerpunkt', 'wohnbaufoerderung', 'artmodell', 'bautraeger', 'architektur', 'aerwachsene', 'akinder', 'awohnungen', 'wohnflaeche', 'gewerbeflaechen', 'gemeinschaftsflaeche', 'sonstige_flaechen', 'flaeche', 'kflaechen', 'gemeinschaftr', 'kgemeinschaftr', 'gewerbe', 'sonderwohnformen', 'raumangebot', 'kraumangebot', 'parbeiten', 'karbeiten', 'bauweise', 'zielgruppen', 'gprojekte', 'oekologie', 'freiraumangebote', 'gaestwohnungen', 'urbanem',
         )

    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['freiraumangebote'].widget  = ListTextWidget(data_list=Wohnprojekt.FREIANGEBOT,  name='freiraumangebote_list')
       # self.fields['gewerbe'].widget     = ListTextWidget(data_list=Wohnprojekt.GEWERBE,  name='gewerbe_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.fields['inseratstext'].label   = "Inseratstext für Raumangebote"
       #
       #
       self.fields['type'].initial  = 'WOHN'
       #
       # self.helper = FormHelper()
       # self.helper.form_tag = False
       self.helper.layout = Layout(
            self.product_layout,

           Fieldset( 'Wohnprojekt',
             'eigentum',
             'artmodell',
             'altneu',
             'schwerpunkt',
             'wohnbaufoerderung',
             'bautraeger',
             'architektur',

              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'),
              'flaeche',
              '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'),
              'gewerbe',
              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', 'urbanem',

           ),
           self.submit_layout,
       )

#
# UPDATE
#





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'),
            ))
