from __future__ import annotations
from enum import Enum
from typing import Union
from common.orm.fields.Field import Field
from common.type_checkers.Checkers import chk_issubclass, chk_options, chk_type
from .Field import Field

class EnumeratedField(Field):
    def __init__(self, enumeration_class : 'Enum', *args, required : bool = True, **kwargs) -> None:
        self.enumeration_class : Enum = chk_issubclass('EnumeratedField.enumeration_class', enumeration_class, Enum)
        super().__init__(*args, type_=self.enumeration_class, required=required, **kwargs)

    def validate(self, value : Union['Enum', str], try_convert_type=False) -> 'Enum':
        value = super().is_required(value)
        if value is None: return None
        if try_convert_type and isinstance(value, str):
            chk_options(self.name, value, self.enumeration_class.__members__.keys())
            value = self.enumeration_class.__members__[value]
        return chk_type(self.name, value, self.enumeration_class)

    def serialize(self, value: 'Enum') -> str:
        value = self.validate(value, try_convert_type=True)
        if value is None: return None
        return str(value.name)
