# Copyright 2021-2023 H2020 TeraFlow (https://www.teraflow-h2020.eu/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

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)
