import logging

from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Q
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse_lazy
from django.views import generic
from django_datatables_view.base_datatable_view import BaseDatatableView

from module_iam import iam_constant, permission
from module_iam.models import IAmPrincipal
from module_project import constants
from module_project.mixins import ActionMixin, DatatablesMixin

from .forms import (AboutUsForm, FaqsForm, PrivacyPolicyForm,
                    TermsAndConditionForm)
from .models import Faqs, Organization

logger = logging.getLogger(__name__)


class FaqView(permission.ResourcePermissionRequiredMixin, LoginRequiredMixin, generic.TemplateView):
    page_name = iam_constant.RESOURCE_MANAGE_FAQS
    resource = iam_constant.RESOURCE_MANAGE_FAQS
    action = None
    template_name = "module_cms/faq.html"
    model = Faqs
    context_objext_name = "obj"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["page_name"] = self.page_name
        return context


class FaqListJson(BaseDatatableView):
    model = Faqs
    columns = ["id", "question", "answer", "active"]
    order_columns = ["id", "question", "answer", "active"]
    FILTER_ICONTAINS = "icontains"

    def get_filter_method(self):
        """Returns preferred filter method"""
        return self.FILTER_ICONTAINS

    def get_initial_queryset(self):
        deleted_flag = self.request.GET.get('deleted_flag', None)

        return self.model.objects.filter(deleted=deleted_flag)

    def ordering(self, qs):
        order = self.request.GET.get('order[0][dir]', None)
        if order:
            column_index = int(self.request.GET.get('order[0][column]', None)) - 1
            order_column = self.order_columns[column_index]

            if order == "asc":
                qs = qs.order_by(order_column)
            elif order == "desc":
                qs = qs.order_by("-" + order_column)

        return qs


class FaqCreateOrUpdateView(permission.ResourcePermissionRequiredMixin, LoginRequiredMixin, generic.View):
    # Set the page_name and resource
    page_name = iam_constant.RESOURCE_MANAGE_FAQS
    resource = iam_constant.RESOURCE_MANAGE_FAQS

    # Initialize the action as ACTION_CREATE (can change based on logic)
    action = iam_constant.ACTION_CREATE   # Default action

    template_name = "module_cms/faq_add.html"
    model = Faqs
    form_class = FaqsForm
    success_url = reverse_lazy("module_cms:faq")
    error_message = "An error occurred while saving the data."

    # Determine the success message dynamically based on whether it's an update or create
    def get_success_message(self):
        self.success_message = (
            constants.RECORD_CREATED if not self.object else constants.RECORD_UPDATED
        )
        return self.success_message

    # Get the object (if exists) based on URL parameter 'pk
    def get_object(self):
        pk = self.kwargs.get("pk")
        return get_object_or_404(self.model, pk=pk) if pk else None

    # Add page_name and operation to the context
    def get_context_data(self, **kwargs):
        context = {
            "page_name": self.page_name,
            "operation": "Add" if not self.object else "Edit",
        }
        context.update(kwargs)  # Include any additional context data passed to the view
        return context

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()

        # If an object is found, change action to ACTION_UPDATE
        if self.object is not None:
            self.action = iam_constant.ACTION_UPDATE

        form = self.form_class(instance=self.object)
        context = self.get_context_data(form=form)
        return render(request, self.template_name, context=context)

    def post(self, request, *args, **kwargs):
        print("Request data: ", request.POST)
        self.object = self.get_object()

        # If an object is found, change action to ACTION_UPDATE
        if self.object is not None:
            self.action = iam_constant.ACTION_UPDATE

        form = self.form_class(request.POST, instance=self.object)
        if not form.is_valid():
            print(form.errors)
            context = self.get_context_data(form=form)
            return render(request, self.template_name, context=context)

        form.save()
        messages.success(self.request, self.get_success_message())
        return redirect(self.success_url)

class FaqActionView(ActionMixin):
    model = Faqs


class FaqArchiveView(permission.ResourcePermissionRequiredMixin, LoginRequiredMixin, generic.TemplateView):
    page_name = iam_constant.RESOURCE_MANAGE_FAQS
    resource = iam_constant.RESOURCE_MANAGE_FAQS
    action = None
    template_name = "module_cms/faq_archive.html"
    model = Faqs

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["page_name"] = self.page_name
        return context

class AboutUsView(permission.ResourcePermissionRequiredMixin, LoginRequiredMixin, generic.DetailView):
    page_name = iam_constant.RESOURCE_MANAGE_CMS
    resource = iam_constant.RESOURCE_MANAGE_CMS
    template_name = "module_cms/about_us_view.html"
    model = Organization
    context_object_name = "organization"

    def get_object(self, queryset=None):
        return self.model.objects.only("about_us").first()

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["page_name"] = self.page_name
        return context


class AboutUsCreateOrUpdateView(permission.ResourcePermissionRequiredMixin, LoginRequiredMixin, generic.View):
    # Set the page_name and resource
    page_name = iam_constant.RESOURCE_MANAGE_CMS
    resource = iam_constant.RESOURCE_MANAGE_CMS
    # Initialize the action as ACTION_CREATE (can change based on logic)
    action = None   # Default action

    template_name = "module_cms/about_us_add.html"
    model = Organization
    form_class = AboutUsForm
    success_url = reverse_lazy("module_cms:about_us")
    error_message = "An error occurred while saving the data."

    # Determine the success message dynamically based on whether it's an update or create
    def get_success_message(self):
        self.success_message = (
            constants.RECORD_CREATED if not self.object else constants.RECORD_UPDATED
        )
        return self.success_message

    # Get the object (if exists) based on URL parameter 'pk'
    def get_object(self):
        return self.model.objects.only("about_us").first()

    # Add page_name and operation to the context
    def get_context_data(self, **kwargs):
        context = {
            "page_name": self.page_name,
            "operation": "Add" if not self.object else "Edit",
        }
        context.update(kwargs)  # Include any additional context data passed to the view
        return context

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()

        # If an object is found, change action to ACTION_UPDATE
        if self.object is not None:
            self.action = None

        form = self.form_class(instance=self.object)
        context = self.get_context_data(form=form)
        return render(request, self.template_name, context=context)

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()

        # If an object is found, change action to ACTION_UPDATE
        if self.object is not None:
            self.action = None

        form = self.form_class(request.POST, instance=self.object)
        if not form.is_valid():
            print(form.errors)
            context = self.get_context_data(form=form)
            return render(request, self.template_name, context=context)

        form.save()
        messages.success(self.request, self.get_success_message())
        return redirect(self.success_url)


class TermsConditionView(permission.ResourcePermissionRequiredMixin, LoginRequiredMixin, generic.DetailView):
    page_name = iam_constant.RESOURCE_MANAGE_T_C
    resource = iam_constant.RESOURCE_MANAGE_T_C
    action = None
    template_name = "module_cms/terms_and_condition_view.html"
    model = Organization
    context_object_name = "organization"

    def get_object(self, queryset=None):
        return self.model.objects.only("terms_condition").first()

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["page_name"] = self.page_name
        return context


class TermsConditionCreateOrUpdateView(permission.ResourcePermissionRequiredMixin, LoginRequiredMixin, generic.View):
    # Set the page_name and resource
    page_name = iam_constant.RESOURCE_MANAGE_T_C
    resource = iam_constant.RESOURCE_MANAGE_T_C

    # Initialize the action as ACTION_CREATE (can change based on logic)
    action = None   # Default action

    template_name = "module_cms/terms_and_condition_edit.html"
    model = Organization
    form_class = TermsAndConditionForm
    success_url = reverse_lazy("module_cms:terms_and_condition")
    error_message = "An error occurred while saving the data."

    # Determine the success message dynamically based on whether it's an update or create
    def get_success_message(self):
        self.success_message = (
            constants.RECORD_CREATED if not self.object else constants.RECORD_UPDATED
        )
        return self.success_message

    # Get the object (if exists) based on URL parameter 'pk'
    def get_object(self):
        return self.model.objects.only("terms_condition").first()

    # Add page_name and operation to the context
    def get_context_data(self, **kwargs):
        context = {
            "page_name": self.page_name,
            "operation": "Add" if not self.object else "Edit",
        }
        context.update(kwargs)  # Include any additional context data passed to the view
        return context

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()

        # If an object is found, change action to ACTION_UPDATE
        # if self.object is not None:
        #     self.action = resource_action.ACTION_UPDATE

        form = self.form_class(instance=self.object)
        context = self.get_context_data(form=form)
        return render(request, self.template_name, context=context)

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()

        # If an object is found, change action to ACTION_UPDATE
        # if self.object is not None:
        #     self.action = resource_action.ACTION_UPDATE

        form = self.form_class(request.POST, instance=self.object)
        if not form.is_valid():
            print(form.errors)
            context = self.get_context_data(form=form)
            return render(request, self.template_name, context=context)

        form.save()
        messages.success(self.request, self.get_success_message())
        return redirect(self.success_url)


class PrivacyPolicyView(permission.ResourcePermissionRequiredMixin, LoginRequiredMixin, generic.DetailView):
    page_name = iam_constant.RESOURCE_MANAGE_PRIVACYPOLICY
    resource = iam_constant.RESOURCE_MANAGE_PRIVACYPOLICY
    action = None
    template_name = "module_cms/privacy_policy_view.html"
    model = Organization
    context_object_name = "organization"

    def get_object(self, queryset=None):
        return self.model.objects.only("privacy_policy").first()

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["page_name"] = self.page_name
        return context


class PrivacyPolicyCreateOrUpdateView(permission.ResourcePermissionRequiredMixin, LoginRequiredMixin, generic.View):
    # Set the page_name and resource
    page_name = iam_constant.RESOURCE_MANAGE_PRIVACYPOLICY
    resource = iam_constant.RESOURCE_MANAGE_PRIVACYPOLICY

    # Initialize the action as ACTION_CREATE (can change based on logic)
    action = None   # Default action

    template_name = "module_cms/privacy_policy_edit.html"
    model = Organization
    form_class = PrivacyPolicyForm
    success_url = reverse_lazy("module_cms:privacy_policy")
    error_message = "An error occurred while saving the data."

    # Determine the success message dynamically based on whether it's an update or create
    def get_success_message(self):
        self.success_message = (
            constants.RECORD_CREATED if not self.object else constants.RECORD_UPDATED
        )
        return self.success_message

    # Get the object (if exists) based on URL parameter 'pk'
    def get_object(self):
        return self.model.objects.only("privacy_policy").first()

    # Add page_name and operation to the context
    def get_context_data(self, **kwargs):
        context = {
            "page_name": self.page_name,
            "operation": "Add" if not self.object else "Edit",
        }
        context.update(kwargs)  # Include any additional context data passed to the view
        return context

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()

        # If an object is found, change action to ACTION_UPDATE
        if self.object is not None:
            self.action = None

        form = self.form_class(instance=self.object)
        context = self.get_context_data(form=form)
        return render(request, self.template_name, context=context)

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()

        # If an object is found, change action to ACTION_UPDATE
        if self.object is not None:
            self.action = None

        form = self.form_class(request.POST, instance=self.object)
        if not form.is_valid():
            print(form.errors)
            context = self.get_context_data(form=form)
            return render(request, self.template_name, context=context)
        form.save()
        messages.success(self.request, self.get_success_message())
        return redirect(self.success_url)
