#coding=utf-8

from rest_framework import serializers
from libs.utils import strftime,strfdate
from util.format import Formater

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 TimeCharField(serializers.CharField):
    def get_attribute(self, obj):
        return obj

    def to_representation(self, obj):
        val = getAttributeValue(self, obj)

        return strftime(val)

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

    def to_representation(self, obj):
        val = getAttributeValue(self, obj)
        return strfdate(val)

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

    def to_representation(self, obj):
        val = getAttributeValue(self, obj)

        return Formater.formatAmountShow(val)

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

    def to_representation(self, obj):
        val = getAttributeValue(self, obj)

        return Formater.formatAmountShowWithTwoDecimalPlaces(val)

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

    def to_representation(self, obj):
        val = getAttributeValue(self, obj)

        return Formater.formatEmptyAmountShow(val)

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

    def to_representation(self, obj):
        val = getAttributeValue(self, obj)

        return Formater.formatPriceShow(val)


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

    def to_representation(self, obj):
        val = getAttributeValue(self, obj)

        return Formater.formatEmptyPriceShow(val)

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

    def to_representation(self, obj):
        val = getAttributeValue(self, obj)

        return Formater.formatCountShow(val)