# -*- coding: utf-8 -*-
import json
import django_filters


class CharInFilter(django_filters.BaseInFilter, django_filters.CharFilter):
    pass


class NumberInFilter(django_filters.BaseInFilter, django_filters.NumberFilter):
    pass


class OneValueMethodFilter(django_filters.CharFilter):
    # todo: test me
    def filter(self, qs, value):
        if not value:
            return qs
        try:
            return getattr(qs, self.field_name)(value)
        except TypeError:
            return qs


class MethodFilter(django_filters.CharFilter):
    def __init__(self, field_name, **kwargs):
        super().__init__(field_name=field_name, **kwargs)

    def filter(self, qs, value):
        if not value:
            return qs
        if value.isdigit():
            args = [value]
        else:
            try:
                args = json.loads(value)
            except ValueError:
                args = value.split(',')
        try:
            return getattr(qs, self.field_name)(*args)
        except TypeError:
            return qs


class BooleanFilter(django_filters.BooleanFilter):
    def __init__(self, true_method_name, false_method_name, *args, **kwargs):
        self.true_method_name = true_method_name
        self.false_method_name = false_method_name
        super(BooleanFilter, self).__init__(*args, **kwargs)

    def filter(self, qs, value):
        if value is not None:
            if value:
                return getattr(qs, self.true_method_name)()
            else:
                return getattr(qs, self.false_method_name)()
        return qs
