# coding=utf8
from __future__ import absolute_import

from rest_framework import serializers


class DateTimeCharField(serializers.CharField):
    def to_representation(self, value):
        ret = super(DateTimeCharField, self).to_representation(value)
        if len(ret) > 19:
            ret = ret[:19]
        return ret


class NamePrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):
    def __init__(self, **kwargs):
        self.select_value = kwargs.pop('select_value', None)
        self.display_key = kwargs.pop('display_key', None)
        self.flag = kwargs.pop('flag', None)
        super(NamePrimaryKeyRelatedField, self).__init__(**kwargs)

    def display_value(self, instance):
        if self.display_key:
            return getattr(instance, self.display_key, '')
        return instance.name

    def to_representation(self, value):
        if self.select_value:
            r = getattr(value, self.select_value, None)
            return r
        return super(NamePrimaryKeyRelatedField, self).to_representation(value)

    def to_internal_value(self, data):
        if self.flag:
            return data
        return super(NamePrimaryKeyRelatedField, self).to_internal_value(data)
