from apps.core.services.filter.search import DynamicSearchService
from rest_framework.exceptions import APIException


class DynamicSearchMixin:
    """ search query sets with introduced fields in view set """

    def get_search_fields(self):
        return getattr(self, "search_fields", [])

    def get_date_field(self):
        return getattr(self, "date_field", "create_date")

    def filter_query(self, queryset):
        queryset = queryset # noqa

        q = self.request.query_params.get("search")  # noqa
        start = self.request.query_params.get("start")  # noqa
        end = self.request.query_params.get("end")  # noqa
        search_fields = self.get_search_fields()
        date_field = self.get_date_field()

        return DynamicSearchService(
            queryset=queryset,
            query_string=q,
            search_fields=search_fields,
            start=start,
            end=end,
            date_field=date_field
        ).apply()


class ExcelDynamicSearchMixin:
    """ search query sets with introduced fields in view set """

    def get_search_fields(self):
        return getattr(self, "search_fields", [])

    def get_date_field(self):
        return getattr(self, "date_field", "create_date")

    def filter_query(self, queryset, search_list=None):
        queryset = queryset # noqa

        q = self.request.query_params.get("search")  # noqa
        start = self.request.query_params.get("start")  # noqa
        end = self.request.query_params.get("end")  # noqa
        if search_list:
            search_fields = search_list
        else:
            search_fields = self.get_search_fields()
        date_field = self.get_date_field()

        return DynamicSearchService(
            queryset=queryset,
            query_string=q,
            search_fields=search_fields,
            start=start,
            end=end,
            date_field=date_field
        ).apply()
