from django.db.models import Q
from django_filters import rest_framework as filter

from console.monitor.models import MonitorPoints, MonitorDevices


class SimCardFilter(filter.FilterSet):
    keyword = filter.CharFilter(method="get_keyword")
    end_time = filter.CharFilter(method="get_end_time")

    def get_end_time(self, queryset, name, value):
        if value:
            year, month = value.split("-")
            queryset = queryset.filter(end_time__year=year,
                                       end_time__month=month)
            return queryset

    def get_keyword(self, queryset, name, value):
        if value:
            monitor_points = MonitorPoints.objects.filter(customer__name__icontains=value)
            sim = MonitorDevices.objects.filter(monitor_point__in=monitor_points).values_list("sim", flat=True)
            queryset = queryset.filter(Q(iccid__icontains=value) |
                                       Q(sim_number__icontains=value) |
                                       Q(operator__icontains=value) |
                                       Q(supplier__icontains=value) |
                                       Q(sim_number__in=sim))
        return queryset
