from decimal import Decimal

from marshmallow import ValidationError, fields


class StrDecimalField(fields.Field):
    # """
    # Field for working with protobuf integers that must be treated as decimals
    # with fixed point position.
    # @:param int places number of digits after decimal point, must be positive
    # """
    # def __init__(self, places: int, **kwargs):
    #     if not isinstance(places, int):
    #         raise TypeError('"places" must be int, not {}'.format(type(places)))
    #     if places <= 0:
    #         raise ValueError('"places" must be positive')
    #
    #     self._places = places
    #     self._coefficient = 10 ** places
    #     super().__init__(**kwargs)

    def _serialize(self, value, attr, obj):
        if not isinstance(value, Decimal):
            raise ValidationError("decimal required (got {})".format(type(value)))

        return str(value)

    def _deserialize(self, value, attr, data):
        if not isinstance(value, str):
            raise ValidationError("str required (got {})".format(type(value)))

        return Decimal(value)
