from rest_framework import serializers


# specialized foreign key serializer which returns a custom
# string if the fk is null
class RelatedFieldNull(serializers.RelatedField):
    # the default implementation does not even bother to call to_native
    # on a empty/null foreign key... therefore we need to trick around a bit here
    # if there is something non None inside it, keep it as it is, since field_to_native
    # already calls to_native, else convert None/Null to some fancy string.
    def field_to_native(self, obj, field_name):
        ret = super(RelatedFieldNull, self).field_to_native(obj, field_name)
        if ret is None:
            from django.utils.html import mark_safe

            return mark_safe('&#8212;')
        else:
            return ret


# enhance date of birth by appending the age
class DOBWithAgeSerializer(serializers.DateField):
    def to_native(self, value):
        from datetime import date

        now = date.today()
        age_years = now.year - value.year - ((now.month, now.day) < (value.month, value.day))
        return '{0} ({1})'.format(value, age_years)


# map boolean values to custom strings, e.g. we don't want to call it qualified: true
# but qualified: yes
class MappedBooleanField(serializers.BooleanField):
    true_label = "true"
    false_label = "false"

    def __init__(self, true_label=str(True), false_label=str(False)):
        self.true_label = true_label
        self.false_label = false_label
        super(MappedBooleanField, self).__init__()

    def to_native(self, value):
        if value:
            return self.true_label
        else:
            return self.false_label


# enhance choice fields with the verbose
class ChoiceFieldVerbose(serializers.CharField):
    choice_list = None

    def __init__(self, choice_list=[]):
        serializers.CharField.__init__(self)
        self.choice_list = choice_list

    def to_native(self, value):
        try:
            for c in self.choice_list:
                if c[0] == value:
                    return c[1]
        except:
            return None
        from django.utils.safestring import mark_safe

        return mark_safe('&#8212;')  # long dash
