import time

from django.utils import timezone
from rest_framework.fields import Field, ReadOnlyField, get_attribute


class FakeField(ReadOnlyField):
    """
    Поле, которое можно использовать, если нужно просто отдать
    в сериализаторе значение как есть
    """
    def __init__(self, fake_value, **kwargs):
        kwargs['source'] = '*'
        super().__init__(**kwargs)
        self._fake_value = fake_value

    def to_representation(self, value):
        return self._fake_value


class MapperField(Field):

    def __init__(self, mapping, **kwargs):
        self.mapping = mapping
        kwargs['read_only'] = True
        super().__init__(**kwargs)

    def to_representation(self, value):
        return self.mapping.get(value)


class StartrekUniqueField(Field):

    def __init__(self, queue, **kwargs):
        self.queue = queue
        kwargs['source'] = '*'
        kwargs['read_only'] = True
        super().__init__(**kwargs)

    def to_representation(self, value):
        return self.generate(value, self.queue)

    @classmethod
    def generate(cls, instance, queue, timestamp_key='created'):
        created = get_attribute(instance, [timestamp_key])
        timestamp = time.mktime(created.timetuple())
        return 'FEMIDA_{queue}_{id}_{timestamp}'.format(
            queue=queue,
            id=get_attribute(instance, ['id']),
            timestamp=timestamp,
        )


class TimeStampField(ReadOnlyField):

    def __init__(self, **kwargs):
        kwargs['source'] = '*'
        super().__init__(**kwargs)

    def to_representation(self, value):
        return timezone.now().isoformat()


class StartrekLocalField:

    def bind(self, field_name, parent):
        super().bind(self.local_field_name, parent)

    @classmethod
    def new(cls, local_field_name, field_class=ReadOnlyField, **kwargs):
        klass = type(cls.__name__, (cls, field_class), {'local_field_name': local_field_name})
        return klass(**kwargs)
