import csv
import json
import copy
import itertools
from PIL import Image
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw

from django.contrib import messages
from django.contrib.auth import login, authenticate
from django.contrib.auth.models import User
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User, Group
from django.core import serializers
from django.core.files import File
from django.core.mail import send_mail
from django.core.exceptions import PermissionDenied
from django.urls import reverse, reverse_lazy
from django.http import HttpResponseRedirect, Http404, HttpResponse
from django.db import models
from django.db.models import Count
from django.views import generic, View
from django.views.generic import TemplateView
from django.views.generic import FormView
from django.views.generic.edit import *
from django.views.generic.detail import *
from django.shortcuts import render, get_object_or_404, redirect, get_list_or_404, get_object_or_404
from django.forms import formset_factory
from django.forms import BaseModelFormSet
from django.forms import modelformset_factory, inlineformset_factory
from django.forms.models import model_to_dict
# from django_countries import countries
from django.template import Context, Template
from django.conf import settings

from django_file_form.uploader import FileFormUploader
from constance import config
from django.db.models import Q
from newsletter.forms import *
from newsletter.views import *
from post_office import mail

from .models import *
from .forms import *
from .utils import *

# Create your views here.
def index(request):
    context = {}
    return render(request, 'index.html', context = context)

def about(request):
    context = {}
    context = {'generic_text': Template(config.ABOUT_CONTENT).render(Context(context))}
    return render(request, 'marktplatz/generic_text.html', context)

def submit(request):
    context = {}
    context = {'generic_text': Template(config.SUBMIT_TEXT).render(Context(context))}
    return render(request,'marktplatz/generic_text.html', context)

def error_404_view(request, exception):
    data = {"name": "Markplatz"}
    return render(request,'marktplatz/error_404.html', data)

@login_required
def home(request):
    user = request.user
    if user.groups.filter(name='submission').exists():
        return HttpResponseRedirect(reverse('meine-projekte'))
    else:
        return  HttpResponseRedirect(reverse('products'))


class genericView(TemplateView):
    template_name =  'marktplatz/generic.html'
    def get(self, request, *args, **kwargs):
        instance = get_object_or_404(Wohnprojekt, pk=2 )
        context = {}
        context['object'] = model_to_dict ( instance )
        context['object']['myfield'] = '----------------------------'
        return render(request, self.template_name, context )



class pagesView(TemplateView):
    template_name =  'marktplatz/generic.html'
    def get(self, request, *args, **kwargs):
        context = {}
        context['content_a'] = ""
        context['content_b'] = config
        # print (config.items() )

        if 'page' in kwargs:
            context['content_a'] = kwargs['page']
            try:

                context['content_a'] = '<br><h2>' + kwargs['page'] + "</h2><br><br>"
                context['content_b'] = getattr(config , kwargs['page'], '')
            except KeyError:
                raise Http404
            # if config.get ( kwargs['page'] ) != None:
            #     context['content_b'] = config.get ( kwargs['page'] )
        return render(request, self.template_name, context )



class ContactUpdateView(LoginRequiredMixin, UpdateView):
    template_name = 'marktplatz/form.html'
    model = Contact
    form_class = RegisterForm
    success_url = reverse_lazy('index')

    def get_object(self, queryset=None):
        obj = super().get_object()
        if (  obj.user_can_manage(self.request.user)  ):
            return obj
        raise PermissionDenied


class  SubscribeRequestView( SubscribeRequestView):

    form_class = NewsletterForm

class AgentNewslwtterFormView(TemplateView):
    template_name =  'marktplatz/form_newsletter.html'
    embed = False

    def get_context_data(self, **kwargs):
        if self.embed :
            kwargs['embed']       = True
            kwargs['form_content']       = '<i  class="fas fa-bell"></i> Suchagent einrichten'
            kwargs['content_a']       = 'Dein Suchagent wurde erstellt!'
        return super().get_context_data(**kwargs)

    def get(self, request, *args, **kwargs):
        context = self.get_context_data()
        context['form'] = AgentNewslwtterForm(  )
        context['bz'] = request.GET.get('bz', '') # used in template to check a district by default.
        return render(request, self.template_name, context )

class AgentNewsletterSubscribeView( SubscribeRequestView ):
    action = 'subscribe'
    # form_class = AgentNewslwtterForm
    confirm = False
    embed = False

    def get_context_data(self, **kwargs):
        if self.embed :
            kwargs['embed']       = True
            kwargs['form_content']       = '<i  class="fas fa-bell"></i> Suchagent einrichten'
            kwargs['content_a']       = 'Dein Suchagent wurde erstellt!'

        # kwargs['news_form']       =  SubscribeRequestForm()
        return super().get_context_data(**kwargs)

    def post(self, request, *args, **kwargs):

        data = request.POST.copy()
        data["email"] = data["email_field"]

        agent_form = AgentNewslwtterForm ( data )

        if agent_form.is_valid():
            agent_form.save()
        else:
            context = {}
            context['form_errors'] = agent_form.errors
            context['form'] = agent_form
            return render(request, 'marktplatz/form_newsletter.html', context )

        if agent_form.cleaned_data['subscribe'] :
            return super().post( request, *args, **kwargs )
            # return super(SubscribeRequestView, self).post( request, *args, **kwargs )


        context = {}
        context['content_a'] = '<br><i  class="fas fa-bell"></i><br><h2>Dein Suchagent wurde erstellt!</h2>'
        return render(request, 'marktplatz/generic.html', context )

    # def dispatch(self, request, *args, **kwargs):
    #
    #     return super(SubscribeRequestView, self).dispatch( request, *args, **kwargs )




class SearchAgentCreate(CreateView):
    model = SearchAgent
    template_name =  'marktplatz/form.html'
    fields =  'ort', 'email'
    success_url = reverse_lazy('generic')
    embed = False


    def get_context_data(self, **kwargs):
            if self.embed :
                kwargs['embed']       = True
                kwargs['form_content']       = '<i  class="fas fa-bell"></i> Suchagent einrichten'
                kwargs['content_a']       = 'Dein Suchagent wurde erstellt!'

            # kwargs['news_form']       =  SubscribeRequestForm()
            return super().get_context_data(**kwargs)


    def form_valid(self, form):
        super().form_valid(form)
        return render(self.request, 'marktplatz/generic.html',
                      self.get_context_data(form=form))


class SearchAgentDelete(DeleteView):
    model = SearchAgent
    template_name =  'marktplatz/form_delete.html'
    success_url = reverse_lazy('products')

    def get(self, request, *args, **kwargs):

        searchagent = get_object_or_404(SearchAgent, pk= kwargs.get('pk') )
        context = {}
        context['form_content'] = 'Dein Suchagent wurde gelöscht!'
        if searchagent.hash == kwargs.get('hash'):
            return super().get(self, request, *args, **kwargs)
        else:
            context['form_content'] = 'Oopala, das hat nicht geklappt.'
            return render(request, self.template_name, context )



class ProductDelete(LoginRequiredMixin, DeleteView):
    model = Product
    template_name =  'marktplatz/product_delete.html'
    success_url = reverse_lazy('products')


    def get(self, request, *args, **kwargs):

        contact = get_object_or_404(Contact, user= self.request.user ) # Contact.objects.get(user=self.request.user)
        product = get_object_or_404(Product, pk= kwargs.get('pk') )

        if (contact.id == product.contact.id) :
            return super(ProductDelete, self).get(self, request, *args, **kwargs)
        else:
            raise Http404

    def post(self, request, *args, **kwargs):

        contact = get_object_or_404(Contact, user= self.request.user ) # Contact.objects.get(user=self.request.user)
        product = get_object_or_404(Product, pk= kwargs.get('pk') )

        if (contact.id == product.contact.id) :
            # context = {}
            # context['form_content'] = 'Dein Projekt wird gelöscht, wenn die Seite live ist!'
            # if settings.DEBUG:
            #     return render(request, self.template_name, context )
            # else:
            return super().post(self, request, *args, **kwargs)
        else:
            raise Http404

        context = {}
        context['form_content'] = 'Oopala, das hat nicht geklappt.'
        return render(request, self.template_name, context )


class ProductPublish(LoginRequiredMixin, DetailView):
    model = Product
    template_name =  'marktplatz/generic.html'
    # success_url = reverse_lazy('products')

    #
    def get(self, request, *args, **kwargs):

        contact = get_object_or_404(Contact, user= self.request.user ) # Contact.objects.get(user=self.request.user)
        product = get_object_or_404(Product, pk= kwargs.get('pk') )


        if (contact.id == product.contact.id) :

            product_url = reverse( 'product-detail', kwargs=  { 'pk': product.pk } )
            publishmessage = "Ein Benutzer möchte folgendes Projekt freigeben: {}, {}".format( product.name, request.get_host() + product_url )

            print (publishmessage)

            userList =User.objects.filter( is_superuser = 1  )
            for superuser in userList:
                mail.send(
                    superuser.email, # List of email addresses also accepted
                    config.EMAIL_NOREPLY,
                    subject='Projekt Freischaltung',
                    headers={  'Reply-To': superuser.email },
                    message= publishmessage,
                    # html_message='Hi <strong>there</strong>!',
                )
            context = {}
            context["content_a"] = '<br><br><br>Die Freigabe wurde beantragt.<br><br><br>'
            return render(request, self.template_name, context )

        else:
            raise Http404

    def post(self, request, *args, **kwargs):
        return self.get(self, request, *args, **kwargs)









class ProductsView(generic.ListView):
    model = Product
    template_name = 'marktplatz/product_overview.html'
    context_object_name = 'object_list'

    def get_queryset(self):

        qs = super().get_queryset()

        user = self.request.user

        qs = qs.order_by('frei')

        if user.groups.filter(name='submission').exists():
            contact = Contact.objects.get(user=user)
            return qs.filter(contact = contact)

        if user.is_superuser:
            return qs

        qs = qs.filter(public = True)

        return qs


    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        orts = {}
        urbanem = False
        for product in context['object_list']:
            if not product.ort in orts:
                orts[product.ort] = product.get_ort_display()
            if hasattr(product, "urbanem"):
                urbanem = True

        context['ort_dict'] = orts
        context['urbanem'] = urbanem

        context['user'] = self.request.user
        context['frei_list'] = Product.FREI
        context['status_list'] = Product.STATUS
        context['sponsor_cards'] =  Template( config.SPONSOR_CARDS ).render( Context(context) )
        context['main_card'] =      Template( config.MAIN_CARD ).render( Context(context) )
        context['type'] = 'BASE'

        context['textSearchForm'] = textSearchForm()

        return context

class WohnprojekteView(ProductsView):
    model = Wohnprojekt
    template_name = 'marktplatz/product_overview.html'
    context_object_name = 'object_list'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        raum_agebote = {}

        for product in context['object_list']:
            for raum in product.raumangebot:
                if not (raum in raum_agebote):
                    raum_agebote[raum] = product.raumangebot.choices[raum]

        context['raum_agebote_dict'] = raum_agebote
        context['frei_list'][0] =  ('JAJA', 'Platz frei')
        context['altneu_list'] = Wohnprojekt.ALTNEU
        context['type'] = 'WOHN'

        return context

class MobilitaetsProjekteView(ProductsView):
    model = MobilitaetsProjekt
    template_name = 'marktplatz/product_overview.html'
    context_object_name = 'object_list'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['type'] = 'MOBI'
        return context


class ErnaerungsProjekteView(ProductsView):
    model = ErnaehrungsProjekt
    template_name = 'marktplatz/product_overview.html'
    context_object_name = 'object_list'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['type'] = 'ERNA'
        return context


class EnergyProjekteView(ProductsView):
    model = EnergyProjekt
    template_name = 'marktplatz/product_overview.html'
    context_object_name = 'object_list'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['type'] = 'ENER'
        return context


class FilterProductsView(ProductsView):


    def get_queryset(self, qfilter=None, **kwargs ):
        # original qs
        qs = super().get_queryset()

        if qfilter!=None:
            mfilter = {}
            mfilter[qfilter] = True
            qs =  qs.filter ( **mfilter  )

        qs = qs.order_by('frei')

        return qs.filter(public = True)

    def get(self, request, *args, **kwargs):

        qfilter = kwargs.get(  'filter', ""  )
        if qfilter != "":
            self.object_list = self.get_queryset(  qfilter = qfilter  )

        allow_empty = self.get_allow_empty()

        context = self.get_context_data()
        return self.render_to_response(context)



class UrbanemProductsView(WohnprojekteView):


    def get_queryset(self, qfilter=None, **kwargs ):
        # original qs
        qs = super().get_queryset()

        if qfilter!=None:
            mfilter = {}
            mfilter[qfilter] = True
            qs =  qs.filter ( **mfilter  )

        qs = qs.order_by('frei')

        return qs.filter(public = True)

    def get(self, request, *args, **kwargs):

        qfilter = 'urbanem'
        if qfilter != "":
            self.object_list = self.get_queryset(  qfilter = qfilter  )

        allow_empty = self.get_allow_empty()

        context = self.get_context_data()
        return self.render_to_response(context)



class SearchProductsView(ProductsView):


    def get_queryset(self, qfilter=None, **kwargs ):
        # original qs
        qs = super().get_queryset()

        user = self.request.user

        if qfilter!=None:
            qs =    qs.filter (name__icontains= qfilter) | \
                    qs.filter (claim__icontains= qfilter) | \
                    qs.filter (beschreibung__icontains= qfilter) | \
                    qs.filter (learning__icontains= qfilter) | \
                    qs.filter (status__icontains= qfilter) | \
                    qs.filter (adresse__icontains= qfilter) | \
                    qs.filter (plz__icontains= qfilter) | \
                    qs.filter (adresse__icontains= qfilter) | \
                    qs.filter (ort__icontains= qfilter) | \
                    qs.filter (website__icontains= qfilter) | \
                    qs.filter (email__icontains= qfilter) | \
                    qs.filter (kfrei__icontains= qfilter) | \
                    qs.filter (rechtsform__icontains= qfilter) | \
                    qs.filter (orga__icontains= qfilter)
            # qs =  qs.filter ( stringToSearch__icontains= qfilter )

        qs = qs.order_by('frei')

        return qs.filter(public = True)

    def post(self, request, *args, **kwargs):

        qform = textSearchForm( request.POST )
        if qform.is_valid():
            self.object_list = self.get_queryset(qfilter= qform.cleaned_data["searchText"]  )


        allow_empty = self.get_allow_empty()

        if not allow_empty:
            # When pagination is enabled and object_list is a queryset,
            # it's better to do a cheap query than to load the unpaginated
            # queryset in memory.
            if self.get_paginate_by(self.object_list) is not None and hasattr(self.object_list, 'exists'):
                is_empty = not self.object_list.exists()
            else:
                is_empty = not self.object_list
            if is_empty:
                raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.") % {
                    'class_name': self.__class__.__name__,
                })
        context = self.get_context_data()
        context['type']=   kwargs['type']
        return self.render_to_response(context)





class SearchWohnProjectsView(SearchProductsView):

    model = Wohnprojekt
    form_class = WohnprojektForm


    def get_queryset(self, qfilter=None, **kwargs ):
        # original qs
        qs = super().get_queryset()

        user = self.request.user

        if qfilter!=None:
            qs =    qs.filter (name__icontains= qfilter) | \
                    qs.filter (claim__icontains= qfilter) | \
                    qs.filter (beschreibung__icontains= qfilter) | \
                    qs.filter (learning__icontains= qfilter) | \
                    qs.filter (status__icontains= qfilter) | \
                    qs.filter (adresse__icontains= qfilter) | \
                    qs.filter (plz__icontains= qfilter) | \
                    qs.filter (adresse__icontains= qfilter) | \
                    qs.filter (ort__icontains= qfilter) | \
                    qs.filter (website__icontains= qfilter) | \
                    qs.filter (email__icontains= qfilter) | \
                    qs.filter (kfrei__icontains= qfilter) | \
                    qs.filter (rechtsform__icontains= qfilter) | \
                    qs.filter (orga__icontains= qfilter) | \
                    qs.filter (eigentum__icontains= qfilter) | \
                    qs.filter (schwerpunkt__icontains= qfilter) | \
                    qs.filter (artmodell__icontains= qfilter) | \
                    qs.filter (bautraeger__icontains= qfilter) | \
                    qs.filter (architektur__icontains= qfilter) | \
                    qs.filter (kflaechen__icontains= qfilter) | \
                    qs.filter (gemeinschaftr__icontains= qfilter) | \
                    qs.filter (kgemeinschaftr__icontains= qfilter) | \
                    qs.filter (raumangebot__icontains= qfilter) | \
                    qs.filter (kraumangebot__icontains= qfilter) | \
                    qs.filter (gewerbe__icontains= qfilter) | \
                    qs.filter (inseratstext__icontains= qfilter) | \
                    qs.filter (sonderwohnformen__icontains= qfilter) | \
                    qs.filter (karbeiten__icontains= qfilter) | \
                    qs.filter (bauweise__icontains= qfilter) | \
                    qs.filter (zielgruppen__icontains= qfilter) | \
                    qs.filter (gprojekte__icontains= qfilter) | \
                    qs.filter (oekologie__icontains= qfilter) | \
                    qs.filter (freiraumangebote__icontains= qfilter)

            # qs =  qs.filter ( stringToSearch__icontains= qfilter )

        qs = qs.order_by('frei')

        return qs.filter(public = True)




class GenericSearchView(SearchProductsView):


    def  dispatch(self, request, *args, **kwargs):

        print( kwargs['type'] )
        if self.kwargs['type'] == 'BASE':
            return super().dispatch(request, *args, **kwargs)
        elif self.kwargs['type'] == 'WOHN':
            return SearchWohnProjectsView.as_view()(request, *args, **kwargs)
        elif self.kwargs['type'] == 'MOBI':
            self.model = MobilitaetsProjekt
            self.form_class = MobilitaetsForm
            return super().dispatch(request, *args, **kwargs)
        elif self.kwargs['type'] == 'ERNA':
            self.model = ErnaehrungsProjekt
            self.form_class = ErnaehrungsForm
            return super().dispatch(request, *args, **kwargs)
        elif self.kwargs['type'] == 'ENER':
            self.model = EnergyProjekt
            self.form_class = EnergyForm
            return super().dispatch(request, *args, **kwargs)



class ProductsListView(generic.ListView):
    model = Product
    template_name='marktplatz/object_list.html'
    embed = False

    def get_queryset(self):
        # original qs
        qs = super().get_queryset()

        self.user = self.request.user
        user = self.user

        if user.is_superuser:
            return qs

        qs = qs.filter(public = True)

        return qs


    def get_context_data(self, **kwargs):

        if self.embed :
            kwargs['embed']  = True
        return super().get_context_data(**kwargs)



#
# DETAIL
#

class ProduktDetailView(generic.DetailView):
    model = Product
    template_name = 'marktplatz/product_detail.html'
    embed = False

    def get_context_data(self, **kwargs):

            if self.embed :
                kwargs['embed'] = True
            return super().get_context_data(**kwargs)

    def post(self, request, *args, **kwargs):
        # vote = int(request.POST['vote'])
        comment = str(request.POST['comment'])

        return HttpResponseRedirect(  reverse('products')  )

class ProduktGenericDetailView(ProduktDetailView):

    def  dispatch(self, request, *args, **kwargs):

        if self.kwargs['type'] == 'BASE':
            super().dispatch(request, *args, **kwargs)
        elif self.kwargs['type'] == 'WOHN':
            self.model = Wohnprojekt
            return super().dispatch(request, *args, **kwargs)
        elif self.kwargs['type'] == 'MOBI':
            self.model = MobilitaetsProjekt
            return super().dispatch(request, *args, **kwargs)
        elif self.kwargs['type'] == 'ERNA':
            self.model = ErnaehrungsProjekt
            return super().dispatch(request, *args, **kwargs)
        elif self.kwargs['type'] == 'ENER':
            self.model = EnergyProjekt
            return super().dispatch(request, *args, **kwargs)

        raise Http404('Keine Objekte gefunden')

class WohnprojektDetailView(ProduktDetailView):
    model = Wohnprojekt
    template_name = 'marktplatz/product_detail.html'

class MobilitaetsProjektDetailView(ProduktDetailView):
    model = MobilitaetsProjekt
    template_name = 'marktplatz/product_detail.html'

class ErnaehrungsProjektDetailView(ProduktDetailView):
    model = ErnaehrungsProjekt
    template_name = 'marktplatz/product_detail.html'

class EnergyProjektProjektDetailView(ProduktDetailView):
    model = EnergyProjekt
    template_name = 'marktplatz/product_detail.html'

class ProduktCardDetailView(ProduktDetailView):

    template_name = 'marktplatz/product_detail_card.html'



#
#
# CREATE CREATE CREATE CREATE CREATE CREATE CREATE CREATE CREATE
#
#


class ProductDispatchView(TemplateView):

    template_name = 'marktplatz/product_create_dispatch.html'


class ProductCreateView(LoginRequiredMixin, CreateView):
    template_name = 'marktplatz/product_create.html'
    model = Product
    form_class = ProductForm
    gotoPics = False
    # success_url = reverse_lazy('meine-projekte')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['info_txt'] = Template(config.INFO_TXT).render(Context(context))
        return context

    def get_success_url(self):
        return reverse_lazy('meine-projekte')

    def post(self, request, *args, **kwargs):
        if 'add-image' in request.POST:
            self.gotoPics = True
        return super().post(self, request, *args, **kwargs)

    def form_valid(self, form):
        product = form.save(commit=False)
        product.contact = Contact.objects.get(user = self.request.user)
        product.save()

        self.object = product

        return HttpResponseRedirect(self.get_success_url())


class ProductGenericCreateView(ProductCreateView):

    def  dispatch(self, request, *args, **kwargs):
        if self.kwargs['type'] == 'BASE':
            super().dispatch(request, *args, **kwargs)
        elif self.kwargs['type'] == 'WOHN':
            self.model = Wohnprojekt
            self.form_class = WohnprojektForm
            return super().dispatch(request, *args, **kwargs)
        elif self.kwargs['type'] == 'MOBI':
            self.model = MobilitaetsProjekt
            self.form_class = MobilitaetsForm
            return super().dispatch(request, *args, **kwargs)
        elif self.kwargs['type'] == 'ERNA':
            self.model = ErnaehrungsProjekt
            self.form_class = ErnaehrungsForm
            return super().dispatch(request, *args, **kwargs)
        elif self.kwargs['type'] == 'ENER':
            self.model = EnergyProjekt
            self.form_class = EnergyForm
            return super().dispatch(request, *args, **kwargs)

        raise Http404('Keine Objekte gefunden' )

class ProductCreateAddPicsView (ProductGenericCreateView):

    def get_success_url(self):
        return reverse_lazy('add-image',  kwargs={'pk': self.object.id }  )


class ProductCreatePublishView (ProductGenericCreateView):

    def get_success_url(self):
        return reverse_lazy('product-publish',  kwargs={'pk': self.object.id }  )




#
#
# UPDATE UPDATE UPDATE UPDATE UPDATE UPDATE UPDATE
#
#


class ProductUpdateView(LoginRequiredMixin, UpdateView):
    template_name = 'marktplatz/product_create.html'
    model = Product
    form_class = ProductForm
    gotoPics = False
    # success_url =

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['info_txt'] = Template(config.INFO_TXT).render(Context(context))
        return context

    def get_success_url(self):
        return reverse_lazy('meine-projekte')

    def get_object(self, queryset=None):
        obj = super().get_object()
        if (  obj.user_can_manage(self.request.user)  ):
            return obj
        raise PermissionDenied

    def post(self, request, *args, **kwargs):
        if 'add-image' in request.POST:
            self.gotoPics = True
        return super().post(self, request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        return super().get(self, request, *args, **kwargs)

    def form_valid(self, form):

        product = form.save(commit=False)
        product.contact = Contact.objects.get(user = self.request.user)
        product.save()

        self.object = product

        return HttpResponseRedirect(self.get_success_url())


class ProductGenericUpdateView(ProductUpdateView):

    model = Product
    form_class = ProductForm

    def  dispatch(self, request, *args, **kwargs):

        if self.kwargs['type'] == 'BASE':
            super().dispatch(request, *args, **kwargs)
        elif self.kwargs['type'] == 'WOHN':
            self.model = Wohnprojekt
            self.form_class = WohnprojektForm
            return super().dispatch(request, *args, **kwargs)
        elif self.kwargs['type'] == 'MOBI':
            self.model = MobilitaetsProjekt
            self.form_class = MobilitaetsForm
            return super().dispatch(request, *args, **kwargs)
        elif self.kwargs['type'] == 'ERNA':
            self.model = ErnaehrungsProjekt
            self.form_class = ErnaehrungsForm
            return super().dispatch(request, *args, **kwargs)
        elif self.kwargs['type'] == 'ENER':
            self.model = EnergyProjekt
            self.form_class = EnergyForm
            return super().dispatch(request, *args, **kwargs)

        raise Http404('Keine Objekte gefunden' )


class ProductUpdateAddPicsView (ProductGenericUpdateView):

    def get_success_url(self):
        return reverse_lazy('add-image',  kwargs={'pk': self.object.id }  )


class ProductUpdatePublishView (ProductGenericUpdateView):

    def get_success_url(self):
        return reverse_lazy('product-publish',  kwargs={'pk': self.object.id }  )



#
# USERS USERS USERS USERS USERS USERS USERS USERS
#



class UsersProducts(LoginRequiredMixin, generic.ListView):
    model = Product
    template_name='marktplatz/myProducts.html'

    def get_queryset(self):
        contact = Contact.objects.get(user=self.request.user)

        wohnprojekte = Wohnprojekt.objects.filter(contact=contact)
        mobilitaetsprojekte = MobilitaetsProjekt.objects.filter(contact=contact)
        ernaehrungsprojekte = ErnaehrungsProjekt.objects.filter(contact=contact)
        energyprojekte = EnergyProjekt.objects.filter(contact=contact)

        projekte = list(itertools.chain(wohnprojekte, mobilitaetsprojekte, ernaehrungsprojekte, energyprojekte))

        return projekte

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        contact = Contact.objects.get(user=self.request.user)

        context['user'] = self.request.user
        return context







class AdminView(LoginRequiredMixin, generic.ListView):
    model = Product
    template_name='marktplatz/admin_panel.html'

    def get_context_data(self, **kwargs):
            context = super().get_context_data(**kwargs)
            return context

    def post(self, request, *args, **kwargs):
        # print (request.POST.dict())
        context = request.POST.dict()
        public = {k: v for k, v in context.items() if k.startswith('product_p')}

        for elemk in public:
            keys = elemk.split(".")
            current_product = Product.objects.get(pk=keys[1])
            if public[elemk] == 'true':
                if current_product.public == False :
                    current_product.public = True
                    current_product.save()
            else:
                current_product.public = False
                current_product.save()


        return HttpResponseRedirect('')




class registerView(FormView):

    template_name = 'marktplatz/form.html'
    # form_class = RegisterForm

    def get(self, request):
        # form = self.form_class()
        context = request.GET.dict()
        context['form_content'] = '<p>Willkommen! Wir freuen uns, dass du bei uns mitmachen willst!</p> <p>Nach der Registrierung kannst du euer Projekt eintragen.</p> <p><br />Evtl. m&ouml;chtest du Kollegen die M&ouml;glichkeit geben auch zum Projekteintrag beizutragen. Wir haben nichts dagegen, dass du deine Logindaten mit Anderen aus deiner Projektgemeinschaft teilst. Dann k&ouml;nnen sie dir beim Eintragen helfen. Man kann Projekteintr&auml;ge &uuml;brigens auch zwischenspeichern, sodass ihr zeitversetzt daran arbeiten k&ouml;nnt. Wenn mehrere diesen Account teilen w&auml;hle dein Passwort mit Bedacht!</p>'
        context['form'] = RegisterForm
        context['signUp'] = SignUpForm

        return render(request, self.template_name, context)

    def post(self, request):

        # print (  request.POST.dict()  )
        form = SignUpForm(request.POST)
        form_contact = RegisterForm(request.POST)


        #
        # Filter existing emails
        #
        qs = Contact.objects.filter(  email=form_contact.data['email']  )
        if (  qs.count()  ):
            form_contact.add_error('email', "Email already in use, please reset your password.")


        if form.is_valid() and form_contact.is_valid():


            # print (form.cleaned_data)
            # print (form_contact.cleaned_data)

            contact = form_contact.save(commit=False)
            user = form.save()

            user.email = contact.email
            user.first_name = contact.first_name
            user.last_name  = contact.last_name
            user.set_password(form.cleaned_data.get('password1'))
            user.save()

            contact.user = user
            contact.save()

            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')

            group = Group.objects.get(name='submission')
            group.user_set.add(user)

            user = authenticate(username=username, password=raw_password)

            if user is not None:
                # A backend authenticated the credentials
                login(request, user)
                return redirect('products')
            else:
                # No backend authenticated the credentials

                send_mail(
                    'error with auth',
                    'Error in authorization.' + json.dumps(  request.POST.dict()  ),
                    'awards@berta.mediaarchitecture.org',
                    ['juan@mediaarchitecture.org'],
                    fail_silently=False,
                )


                return redirect('products')

            login(request, user)

        else:


            # print (form.errors)
            # print (form_contact.errors)

            send_mail(
                'error with auth',
                'Error in forms. \n\n form.errors: \n\n' +  json.dumps(form.errors) + '\n\n form_contact.errors: \n\n' + json.dumps(form_contact.errors),
                'awards@berta.mediaarchitecture.org',
                ['juan@mediaarchitecture.org'],
                fail_silently=False,
            )


            context = request.POST.dict()

            context['signUp'] = form
            context['form'] = form_contact

            context['signup_errors']  = form.errors
            context['contact_errors'] = form_contact.errors

            return render(request, self.template_name, context)


        context = request.GET.dict()
        context['form'] = RegisterForm
        context['signUp'] = SignUpForm

        return render(request, self.template_name, context)



class lightboximg(LoginRequiredMixin, TemplateView):

    template_name = "marktplatz/importold.html"

    def post(self, request):
        context = {'faild': ''}
        faild = ''
        from1 = int(request.POST['from'])
        to = int(request.POST['to'])


        products = Product.objects.all()
        i = 0

        for product in products:
            i+=1
            if (i < from1):
                continue
            if (i > to):
                break

            medias = product.media_set.all()
            for oldmedia in medias:
                if not oldmedia.image_norm:
                    oldpic = oldmedia.image
                    oldmedia.image_norm.save(oldmedia.filename() + '_norm', oldpic)
                    oldmedia.save


        return render(request, self.template_name, context)



    def get(self, request):
            context = {'faild': ''}
            faild = ''
            context['faild'] = faild
            return render(request, self.template_name, context)


class addImageView(LoginRequiredMixin, FormView):
    use_ajax = True
    template_name = 'marktplatz/file_upload.html'

    def get(self, request, pk):
        user = self.request.user
        contact = Contact.objects.get(user=user)
        # print (contact.id)
        product = Product.objects.filter(contact=contact)

        if not Product.objects.filter(contact=contact).filter(pk=pk).exists():
            # print( "no product 1" )
            raise Http404

        product = Product.objects.get(pk=pk)
        photo = product.media_set.count()
        video = product.video_set.count()

        context = request.GET.dict()
        contact = Contact.objects.get(user=self.request.user)
        # print( "before 404" )
        product = get_object_or_404(Product, (Q(pk=pk) & Q(contact=contact)))
        context['product'] = product
        context['images'] = Media.objects.filter(product=product)
        context['video'] = Video.objects.filter(product=product)
        context['media'] = MediaForm
        context['media_count'] = False
        context['video_count'] = False
        if photo >= 7:
            context['media_count'] = True
        if video >= 2:
            context['video_count'] = True

        # context['use_ajax'] = True
        context['warning'] = False

        return render(request, self.template_name, context)


    def post(self, request, pk):

        vid1_f      = MediaForm(request.POST, request.FILES)
        product = Product.objects.get(pk=pk)
        i = product.media_set.count()
        i += product.video_set.count()

        video = product.video_set.count()
        photo = product.media_set.count()

        context = request.GET.dict()
        contact = Contact.objects.get(user=self.request.user)
        product = get_object_or_404(Product, (Q(pk=pk) & Q(contact=contact)))
        context['product'] = product
        context['images'] = Media.objects.filter(product=product)
        context['video'] = Video.objects.filter(product=product)
        context['media'] = MediaForm
        context['media_count'] = False
        context['video_count'] = False
        context['use_ajax'] = True
        context['warning'] = False

        if vid1_f.is_valid():
            image = vid1_f.cleaned_data['image']
            name = image.name
            if 'png' in name or 'jpg' in name or 'jpeg' in name:
                if photo < 7:
                    vid1 = Media()
                    vid1.product = product
                    vid1.filename = name
                    vid1.copyright = vid1_f.cleaned_data['copyright']
                    vid1.name_for =  vid1_f.cleaned_data['name_for']
                    vid1.image.save(name, image)
                    vid1.image_small.save(str(i) + '_small', image)
                    vid1.image_medium.save(str(i) + '_medium', image)
                    vid1.image_big.save(str(i) + '_big', image)
                    vid1.image_norm.save(str(i) + '_norm', image)
                    vid1.save
                    photo += 1
                else:
                    context['warning'] = "You can not upload any more photos!"


            elif 'mp4' in name or 'm3u8' in name or 'm4v' in name:
                if video < 2:
                    #TODO clean image here!
                    vid1 = Video()
                    vid1.product = product
                    vid1.filename = name
                    vid1.copyright = vid1_f.cleaned_data['copyright']
                    vid1.name_for = vid1_f.cleaned_data['name_for']
                    vid1.image.save(name, image)
                    vid1.save
                    video += 1
                else:
                    context['warning'] = "You can not upload any more videos!"


            vid1_f.delete_temporary_files()

        if photo >= 7:
            context['media_count'] = True
        if video >= 2:
            context['video_count'] = True

        return render(request, self.template_name, context)


handle_upload = FileFormUploader()








def delete_media(request, pk):
    user = request.user
    contact = Contact.objects.get(user=user)
    object = Media.objects.get(id=pk)
    if not Product.objects.filter(contact=contact).filter(pk=object.product.pk).exists():
        raise Http404
    object.delete()
    return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))



def delete_video(request, pk):
    user = request.user
    contact = Contact.objects.get(user=user)
    object = Video.objects.get(id=pk)
    if not Product.objects.filter(contact=contact).filter(pk=object.product.pk).exists():
        raise Http404
    object.delete()
    return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
