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.db import models
from django.db.models import Count
from django.core import serializers
from django.core.files import File
from django.core.mail import send_mail
from django.urls import reverse, reverse_lazy
from django.http import HttpResponseRedirect, Http404, HttpResponse
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.views import generic
from django.views.generic import TemplateView
from django.views.generic import FormView
from django.views.generic.edit 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_file_form.uploader import FileFormUploader
from django_countries import countries
from django.template import Context, Template
from django.conf import settings

from constance import config
from django.db.models import Q
from newsletter.forms import *
from newsletter.views import *

from marktplatz.models import *
from .forms import *

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

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

def submit(request):
    context = {}
    context = {'submit_text': Template(config.SUBMIT_TEXT).render(Context(context))}
    return render(request,'marktplatz/submit.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('my-products'))
    else:
        return  HttpResponseRedirect(reverse('products'))


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(  )
        # print (context)
        return render(request, self.template_name, context )

class AgentNewslwtterSubscribeView(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(SubscribeRequestView).get(self, request, *args, **kwargs)
            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 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'] = '----------------------------'
        # print (context)
        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'] = "lalalala"
        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 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.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'):
            if settings.DEBUG:
                return render(request, self.template_name, context )
            else:
                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 ProductsView(generic.ListView):
    model = Wohnprojekt
    #context_object_name = 'Products'
    # show the best 4 website finish

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

        self.user = self.request.user
        user = self.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)
            user =self.request.user
            context['user'] = user
            used_countries = []
            orts = {}
            raum_agebote = {}

            years = {''}
            for product in context['wohnprojekt_list']:
                print ( type (product.raumangebot) )
                print (  repr(product.raumangebot)  )
                # print (  dir(product.raumangebot)  )
                print (  "----"  )
                print (  product.raumangebot.__dict__  )
                print (  "xxxx"  )
                dir(MultiSelectField)

                print (  dir(product.raumangebot.choices )  )
                # print (  product.get_raumangebot_display  )

                # print ( product.raumangebot.max_length )
                #
                # print ( product.raumangebot.to_python() )


                if not years.__contains__(product.year):
                    years.add(product.year)
                for country in product.country:
                    if not used_countries.__contains__(country):
                        used_countries.append(country)
                # if not used_orts.__contains__(  product.get_ort_display()  ):
                if not product.ort in orts:
                    orts[product.ort] = product.get_ort_display()
                # print (product.raumangebot.get_list() )
                for raum in product.raumangebot:
                    print(raum)
                    # print(raum.get_display() )

                    if not (raum in raum_agebote):
                        raum_agebote[raum] = product.raumangebot.choices[raum]



            years.remove('')
            context['year_list'] = years
            context['count_list'] = used_countries
            context['frei_list'] = Product.FREI
            context['status_list'] = Product.STATUS
            context['ort_dict'] = orts
            context['raum_agebote_dict'] = raum_agebote

            context['altneu_list'] = Wohnprojekt.ALTNEU


            context['sponsor_cards'] =  Template( config.SPONSOR_CARDS ).render( Context(context) )
            context['main_card'] =      Template( config.MAIN_CARD ).render( Context(context) )


            context['textSearchForm'] = textSearchForm()


            return context

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

    template_name = 'marktplatz/product_overview.html'

class SearchProductsView(ProductsView):


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

        self.user = self.request.user
        user = self.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.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()
        return self.render_to_response(context)


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

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

            if self.embed :
                kwargs['embed']       = True
            # context['credits'] = Credit.objects.select_related().get(product = self.kwargs['pk'])
            # context['wohnprojekt'] = self.object.wohnprojekt
            return super().get_context_data(**kwargs)


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


        if vote <= 10:

             try:
                get_vote = Vote.objects.get(juryMember=self.request.user, product=self.kwargs['pk'])

                get_vote.vote = vote
                get_vote.comment = comment
                get_vote.save()


             except Vote.DoesNotExist:

                get_vote = Vote(product = Product.objects.get(pk=self.kwargs['pk']), juryMember= self.request.user, vote = vote, comment=comment)
                get_vote.save()

        else:
            return HttpResponseRedirect(request.path)

        return HttpResponseRedirect(reverse('products'))

class CardDetailView(DetailView):

    template_name = 'marktplatz/product_detail_card.html'

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:
            # print(elemk + " -  " + public[elemk] )
            keys = elemk.split(".")
            current_product = Product.objects.get(pk=keys[1])
            if public[elemk] == 'true':
                current_product.public = True
                current_product.save()
            else:
                current_product.public = False
                current_product.save()

        edit = {k: v for k, v in context.items() if k.startswith('product_e')}
        # print (edit)
        for elemk in edit:
            # print(elemk + " -  " + edit[elemk] )
            keys = elemk.split(".")
            current_product = Product.objects.get(pk=keys[1])
            if edit[elemk] == 'true':
                current_product.edit = True
                current_product.save()
            else:
                current_product.edit = False
                current_product.save()

        return HttpResponseRedirect('')



class ProductsListView(generic.ListView):
    model = Product
    template_name='marktplatz/product_list.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):
        # 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:
            # print(elemk + " -  " + public[elemk] )
            keys = elemk.split(".")
            current_product = Product.objects.get(pk=keys[1])
            if public[elemk] == 'true':
                current_product.public = True
                current_product.save()
            else:
                current_product.public = False
                current_product.save()

        edit = {k: v for k, v in context.items() if k.startswith('product_e')}
        # print (edit)
        for elemk in edit:
            # print(elemk + " -  " + edit[elemk] )
            keys = elemk.split(".")
            current_product = Product.objects.get(pk=keys[1])
            if edit[elemk] == 'true':
                current_product.edit = True
                current_product.save()
            else:
                current_product.edit = False
                current_product.save()

        return HttpResponseRedirect('')



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 registerView(FormView):

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

    def get(self, request):
        # form = self.form_class()
        context = request.GET.dict()
        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 NewProductView(LoginRequiredMixin, FormView):
    use_ajax = True
    template_name = 'marktplatz/add.html'

    model = Product

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

    model = Product

    def get(self, request,*args, **kwargs):
        # form = self.form_class()


        context = request.GET.dict()
        context['product'] =        WohnprojektForm
        context['use_ajax'] = True
        context['info_txt'] = Template(config.INFO_TXT).render(Context(context))


        return render(request, self.template_name, context)


    def post(self, request):

        product_f   = WohnprojektForm(request.POST, request.FILES)

        if product_f.is_valid():

            product   = product_f.save(commit=False)

            product.contact = Contact.objects.get(user = self.request.user)

            product.edit=True
            product.public = False
            product.sumbitted = config.CURRENT_EVENT

            product.save()
            # product_f.save_m2m()

            if 'addImage' in request.POST:
                return HttpResponseRedirect(reverse('add-Image', kwargs={'pk': product.pk}))

            return HttpResponseRedirect(reverse('my-products'))

        else:

            context = request.POST.dict()
            context['product'] =        product_f
            context['product_errors']  = product_f.errors
            context['use_ajax'] = True
            return render(request, self.template_name, context)


class uploadView(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)
        if not Product.objects.filter(contact=contact).filter(pk=pk).exists():
            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)
        product = get_object_or_404(Wohnprojekt, (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()




class EditView(LoginRequiredMixin, FormView):

    template_name = 'marktplatz/add.html'

    def get(self, request, pk):
        user = self.request.user
        contact = Contact.objects.get(user=user)
        if not Product.objects.filter(contact=contact).filter(pk=pk).exists():
                raise Http404

        context = request.GET.dict()

        context['product'] = WohnprojektForm(instance=Wohnprojekt.objects.get(pk=pk))


        context['use_ajax']    =    True
        context['info_txt'] = Template(config.INFO_TXT).render(Context(context))

        return render(request, self.template_name, context)

    def post(self, request, pk):

        product_f = WohnprojektForm(request.POST, request.FILES, instance=Wohnprojekt.objects.get(pk=pk))

        if product_f.is_valid():
            if product_f.has_changed():
                product =  product_f.save( commit=False )
                update_fields = product_f.changed_data
                product.current_uri = request.build_absolute_uri( '/' ).rstrip('/')
                product.save( update_fields=update_fields )
                # product.save( )

            if 'addImage' in request.POST:
                return HttpResponseRedirect(reverse('add-Image', kwargs={'pk': pk}))

            return HttpResponseRedirect(reverse('my-products'))

        else:
            context = request.GET.dict()
            context['product'] =        product_f
            context['product_errors']  = product_f.errors
            context['use_ajax'] = True
            return render(request, self.template_name, context)



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

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

        return Product.objects.filter(contact=contact)

    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 MediaView(LoginRequiredMixin, TemplateView):
    template_name = 'marktplatz/media_overview.html'

    def get(self, request, pk):
        self.user = self.request.user
        user= self.user
        contact = Contact.objects.get(user=user)
        if not Product.objects.filter(contact=contact).filter(pk=pk).exists():
            raise Http404

        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['media'] = Media.objects.filter(product=product)
        context['video'] = Video.objects.filter(product=product)
        return render(request, self.template_name, context)



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