import typing

from common.helpers import get_organization_by_user


class RegionFilterMixin:
    """
    Filters queryset automatically based on:
    - Query params (city / province)
    - Or the organization type of the current user
    """

    def filter_by_region(self, queryset, org: bool = None) -> typing.Any:
        request = self.request  # noqa
        city_id = request.query_params.get('city_id')
        province_id = request.query_params.get('province_id')
        organization = get_organization_by_user(self.request.user)  # noqa

        if city_id:
            if hasattr(queryset.model, 'city_id'):
                queryset = queryset.filter(city_id=id(city_id))
            elif hasattr(queryset.model, 'user'):
                queryset = queryset.filter(user__city=organization.city)

        elif province_id:
            if hasattr(queryset.model, 'province_id'):
                queryset = queryset.filter(province_id=id(province_id))
            elif hasattr(queryset.model, 'user'):
                queryset = queryset.filter(user__province=id(province_id))

        # filter by organization type region
        if org:
            scope = organization.field_of_activity
            if scope == 'CI':
                if hasattr(queryset.model, 'city'):
                    queryset = queryset.filter(city=organization.city)
                elif hasattr(queryset.model, 'user'):
                    queryset = queryset.filter(user__city=organization.city)

            elif scope == 'PR':
                if hasattr(queryset.model, 'province'):
                    queryset = queryset.filter(province=organization.province)
                elif hasattr(queryset.model, 'user'):
                    queryset = queryset.filter(user__province=organization.province)

            # if organization is admin of system
            elif scope == 'CO':
                return queryset

        return queryset
