from django.shortcuts import render, get_object_or_404
from django.views.generic import CreateView, ListView
from django.urls import reverse_lazy
from .forms import ContatoForm, CommentForm, ReservaForm, PasseioCommentForm, PasseioFotoForm
from .models import Contato, Empresa, Produto, Categoria, Galeria, Reserva, Post, Passeio, PasseioFoto
from .models import PaginaPrincipal, FotoPaginaPrincipal, FotoPaginaSobre, ClienteGastro, CategoriaGastro
from .models import GastroDetail
from django.contrib import messages


class IndexView(CreateView):
    template_name = 'index.html'
    model = Contato
    form_class = ContatoForm
    form_class_adicional = ReservaForm
    success_url = reverse_lazy('index')

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)

        context['form'] = self.form_class
        context['form_reserva'] = self.form_class_adicional()

        context['empresa'] = Empresa.objects.all().filter(ativo=True).order_by('?').first()

        context['fotos_principal'] = FotoPaginaPrincipal.objects.all().filter(ativo=True).order_by('?').first()

        context['pagina_principal'] = PaginaPrincipal.objects.all().filter(ativo=True).order_by('?')

        context['fotos_sobre'] = FotoPaginaSobre.objects.all().filter(ativo=True).order_by('?').first()

        categ = Categoria.objects.values('id', 'categoria').all().filter(ativo=True).order_by('-modificado')
        context['categorias'] = categ

        context['produtos'] = Produto.objects.all().order_by('categoria').filter(ativo=True)
        context['first_produto'] = Produto.objects.all().order_by('?').filter(ativo=True).first()

        for cat in categ:
            context[cat['categoria']] = Produto.objects.all().filter(categoria=cat['id']).filter(ativo=True)

        categ_gastro = CategoriaGastro.objects.values('id', 'categoria_gastro', 'imagem').all().filter(ativo=True).order_by('-modificado')
        context['categorias_gastro'] = CategoriaGastro.objects.all().filter(ativo=True).order_by('-modificado')

#        context['clientes_gastro'] = ClienteGastro.objects.all().order_by('categoria_gastro').filter(ativo=True)
        context['first_gastronomia'] = ClienteGastro.objects.all().order_by('?').filter(ativo=True).first()

#        for cat in categ_gastro:
#            context[cat['categoria_gastro']] = ClienteGastro.objects.all().filter(categoria_gastro=cat['id']).filter(ativo=True)

        context['promocoes'] = Produto.objects.all().filter(promocao=True).order_by('?')

        context['f_todas'] = Galeria.objects.all().filter(ativo=True).order_by('-modificado')

        context['reservas'] = Reserva.objects.all().filter(ativo=True).order_by('data').order_by('hora')

        context['post_list'] = Post.objects.all().filter(status=1).order_by('-created_on')

        context['passeio_list'] = Passeio.objects.all().filter(status=1).order_by('-created_on')
        context['first_passeio'] = PasseioFoto.objects.all().order_by('?').first()

        return context

    def form_valid(self, form, *args, **kwargs):
        form.save()
        messages.success(self.request, 'Mensagem enviada !!!')
        return super(IndexView, self).form_valid(form)

    def form_invalid(self, form, *args, **kwargs):
        messages.error(self.request, 'Erro ao enviar mensagem !!!')
        return super(IndexView, self).form_invalid(form)


def gastro_categoria(request, id):
    template_name = 'gastro_categoria.html'
    categoria = CategoriaGastro.objects.all().filter(id=id).first()
    gastronomia = ClienteGastro.objects.all().filter(categoria_gastro=id)
    return render(request, template_name, {'gastronomia': gastronomia,
                                           'gastro_categoria': categoria })


def gastro_detail(request, id):
    template_name = 'gastro_detail.html'
    restaurante = ClienteGastro.objects.all().filter(id=id).first()
    restaurante_detail = GastroDetail.objects.all().filter(restaurante=id)
    return render(request, template_name, {'restaurante_detail': restaurante_detail,
                                           'restaurante': restaurante })


class PostList(ListView):
    queryset = Post.objects.filter(status=1).order_by('-created_on')
    template_name = 'index.html'


def post_detail(request, slug):
    template_name = 'post_detail.html'
    post = get_object_or_404(Post, slug=slug)
    comments = post.comments.filter(active=True)
    new_comment = None
    # Comment posted
    if request.method == 'POST':
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():

            # Create Comment object but don't save to database yet
            new_comment = comment_form.save(commit=False)
            # Assign the current post to the comment
            new_comment.post = post
            # Save the comment to the database
            new_comment.save()
    else:
        comment_form = CommentForm()

    return render(request, template_name, {'post': post,
                                           'comments': comments,
                                           'new_comment': new_comment,
                                           'comment_form': comment_form})


class PasseioList(ListView):
    queryset = Passeio.objects.filter(status=1).order_by('-created_on')
    template_name = 'index.html'


def passeio_detail(request, slug):
    template_name = 'passeio_detail.html'
    passeio = get_object_or_404(Passeio, slug=slug)
    passeio_comments = passeio.passeio_comments.filter(active=True)
    novo_comment = None
    # Comment posted
    if request.method == 'POST':
        passeio_comment_form = PasseioCommentForm(data=request.POST)
        if passeio_comment_form.is_valid():

            # Create Comment object but don't save to database yet
            novo_comment = passeio_comment_form.save(commit=False)
            # Assign the current post to the comment
            novo_comment.passeio = passeio
            # Save the comment to the database
            novo_comment.save()
    else:
        passeio_comment_form = PasseioCommentForm()

    return render(request, template_name, {'passeio': passeio,
                                           'passeio_comments': passeio_comments,
                                           'novo_comment': novo_comment,
                                           'passeio_comment_form': passeio_comment_form})


def passeio_foto_detail(request, slug):
    template_name = 'passeio_foto_detail.html'
    passeio = get_object_or_404(Passeio, slug=slug)
    passeio_fotos = passeio.passeio_fotos.filter(active=True)
    nova_foto = None
    # Comment posted
    if request.method == 'POST':
        passeio_foto_form = PasseioFotoForm(data=request.POST)
        if passeio_foto_form.is_valid():

            # Create Comment object but don't save to database yet
            nova_foto = passeio_foto_form.save(commit=False)
            # Assign the current post to the foto
            nova_foto.passeio = passeio
            # Save the foto to the database
            nova_foto.save()
    else:
        passeio_foto_form = PasseioFotoForm()

    return render(request, template_name, {'passeio': passeio,
                                           'passeio_fotos': passeio_fotos,
                                           'nova_foto': nova_foto,
                                           'passeio_foto_form': passeio_foto_form})


