#coding=utf-8
from django.utils import timezone
from rest_framework import serializers

def getAttributeValue(instance, obj):
    if '.' in instance.source:
        k = instance.source.split('.')
        for i in range(len(k)):
            if hasattr(obj, k[i]):
                obj = getattr(obj, k[i])
        val = obj
    else:
        val = getattr(obj, instance.source)
    return val

class BooleanCharField(serializers.BooleanField):
    def get_attribute(self, obj):
        return obj

    def to_representation(self, obj):
        val = getAttributeValue(self, obj)
        return u'是' if val else u'否'

class DelayTimeCharField(serializers.CharField):
    def get_attribute(self, obj):
        return obj

    def to_representation(self, obj):
        val = getAttributeValue(self, obj)
        delay = timezone.now() - val

        if delay:
            if delay.days:
                delay = u'{}天前'.format(delay.days)
            elif delay.seconds:
                delay = delay.seconds / 60
                if delay < 60:
                    delay =u'{}分钟前'.format(int(delay))
                elif delay < 60 * 24:
                    delay = u'{}小时前'.format(int(delay / 60))
            else:
                delay = u''
        else:
            delay = u''
        return delay