import logging
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from django.views.decorators.http import require_POST
from django.views.generic import ListView, DetailView, TemplateView
from django_ratelimit.decorators import ratelimit

from apps.system.blog.models import Blog
from apps.system.config.models import MailList, Config
from apps.system.contactUs.models import ContactUs
from apps.system.course.models import Course
from apps.system.home.models import Home
from apps.system.testimonial.models import Testimonial


def get_display_course():
    checkDisplayTrue = Course.objects.filter(display=True, status=True).first()
    if not checkDisplayTrue:
        checkDisplayTrue = Course.objects.filter(status=True).order_by('orderBy').first()
    return checkDisplayTrue


def get_infos():
    keys = ['address', 'mobile', 'email', 'facebook', 'instagram', 'twitter', 'address2', 'threads']
    return {key: Config.objects.filter(title=key).first().value or None for key in keys}


@method_decorator(cache_page(60 * 60 * 24 * 30), name='dispatch')
class HomeView(ListView):
    model = Home
    template_name = "frontend/home/index.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['displayCourse'] = get_display_course()
        context['courses'] = Course.objects.filter(status=True).order_by('orderBy')[:6]
        context['blogs'] = Blog.objects.filter(status=True).order_by('orderBy')[:3]
        context['activeHome'] = True
        context['info'] = get_infos
        return context

    def render_to_response(self, context, **response_kwargs):
        response = super().render_to_response(context, **response_kwargs)
        response['Cache-Control'] = 'public, max-age=2592000'  # 30 days
        return response


# @transaction.atomic
@require_POST
@ratelimit(key='ip', rate='1/h')
def store_contact_us(request):
    if getattr(request, 'limited', False):
        return JsonResponse({'status': False, 'message': 'More requests detected, please try again.'}, status=429)

    try:
        name = request.POST.get('name')
        email = request.POST.get('email')
        phone = request.POST.get('phone')
        message = request.POST.get('message')
        ContactUs.objects.create(name=name, email=email, phone=phone, message=message)

        return JsonResponse({'status': True, 'message': 'Thanks for contacting us. We will reach you soon!'})
    except Exception as e:
        logger_api = logging.getLogger('frontend')
        logger_api.info(str(e))
        return JsonResponse({'status': False}, status=400)


# ----------------COURSE START-----------------
@method_decorator(cache_page(60 * 60 * 24 * 30), name='dispatch')
class CourseIndex(ListView):
    model = Course
    template_name = 'frontend/course/index.html'
    context_object_name = 'courses'
    queryset = Course.objects.filter(status=True).order_by('orderBy')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['activeCourse'] = True
        context['info'] = get_infos
        return context


class CourseSlugIndex(DetailView):
    model = Course
    template_name = 'frontend/course/slug.html'
    context_object_name = 'course'

    def get_object(self, queryset=None):
        return get_object_or_404(Course, slug=self.kwargs['slug'], status=True)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['courses'] = Course.objects.filter(status=True).exclude(slug=self.kwargs['slug']).order_by(
            'orderBy')[:3]
        context['activeCourse'] = True
        context['info'] = get_infos

        return context


# ----------------Blog START-----------------
@method_decorator(cache_page(60 * 60 * 24 * 30), name='dispatch')
class BlogIndex(ListView):
    model = Blog
    paginate_by = 9
    template_name = 'frontend/blog/index.html'
    context_object_name = 'blogs'
    queryset = Blog.objects.filter(status=True).order_by('orderBy')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['activeBlog'] = True
        context['info'] = get_infos
        return context


class BlogSlugIndex(DetailView):
    model = Blog
    template_name = 'frontend/blog/slug.html'
    context_object_name = 'blog'

    def get_object(self, queryset=None):
        return get_object_or_404(Blog, slug=self.kwargs['slug'], status=True)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['blogs'] = Blog.objects.filter(status=True).exclude(slug=self.kwargs['slug']).order_by(
            'orderBy')[:10]
        context['activeBlog'] = True
        context['info'] = get_infos

        return context


# ----------------Mail List START-----------------

# @transaction.atomic
@require_POST
@ratelimit(key='ip', rate='1/h')
def store_mail(request):
    if getattr(request, 'limited', False):
        return JsonResponse({'status': False, 'message': 'More requests detected, please try again.'}, status=429)

    try:
        email = request.POST.get('email')
        MailList.objects.filter(email=email).update(unsubscribe=False)
        if not MailList.objects.filter(email=email).exists():
            MailList.objects.create(email=email)

        return JsonResponse({'status': True, 'message': 'Thanks for subscribing us.'})
    except Exception as e:
        logger_api = logging.getLogger('frontend')
        logger_api.info(str(e))
        return JsonResponse({'status': False}, status=400)


# ----------------About US START-----------------
@method_decorator(cache_page(60 * 60 * 24 * 30), name='dispatch')
class AboutUsIndex(ListView):
    model = Home
    template_name = 'frontend/aboutUs/index.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['activeAboutUs'] = True
        context['info'] = get_infos
        return context


# ----------------Contact US START-----------------
@method_decorator(cache_page(60 * 60 * 24 * 30), name='dispatch')
class ContactUsIndex(ListView):
    model = Home
    template_name = 'frontend/contactUs/index.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['activeContactUs'] = True
        context['info'] = get_infos
        return context


# ----------------FAQ START-----------------
@method_decorator(cache_page(60 * 60 * 24 * 30), name='dispatch')
class FaqIndex(ListView):
    model = Home
    template_name = 'frontend/faq/index.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['activeFaq'] = True
        context['info'] = get_infos
        return context


# ----------------Testimonial START-----------------
@method_decorator(cache_page(60 * 60 * 24 * 30), name='dispatch')
class TestimonialIndex(ListView):
    model = Testimonial
    template_name = 'frontend/testimonial/index.html'

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


# ----------------Demart START-----------------
@method_decorator(cache_page(60 * 60 * 24 * 30), name='dispatch')
class DematIndex(ListView):
    model = Home
    template_name = 'frontend/demat/index.html'

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

class LinksIndex(TemplateView):
    template_name = 'frontend/links/index.html'
    
class PartnersIndex(TemplateView):
    template_name = 'frontend/partner/index.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        top_product_titles = [
            'Stock Market Investing For Beginners',
            'Silver Membership',
            'Gold Membership',
            'Platinum Membership',
        ]
        context['courses'] = Course.objects.filter(status=True, title__in=top_product_titles).order_by('orderBy')
        context['info'] = get_infos
        return context

