# 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
import logging
from typing import TYPE_CHECKING, Any, List, Set, Tuple, Union
from common.type_checkers.Checkers import chk_boolean, chk_not_none, chk_string, chk_type

if TYPE_CHECKING:
    from ..model.Model import Model

LOGGER = logging.getLogger(__name__)

# Ref: https://docs.python.org/3.9/howto/descriptor.html

class Field:
    def __init__(
        self, name : str = None, type_ : Union[type, Set[type], Tuple[type], List[type]] = object,
        required : bool = False) -> None:

        self.name = None if name is None else chk_string('Field.name', name)
        self.type_ = chk_type('Field.type', type_, (type, set, tuple, list))
        self.required = chk_boolean('Field.required', required)

    def __get__(self, instance : 'Model', objtype=None):
        if instance is None: return self
        return instance.__dict__.get(self.name)

    def __set__(self, instance : 'Model', value : Any) -> None:
        instance.__dict__[self.name] = self.validate(value)

    def __delete__(self, instance : 'Model'):
        raise AttributeError('Attribute "{:s}" cannot be deleted'.format(self.name))

    def is_required(self, value):
        if self.required:
            chk_not_none(self.name, value, reason='is required. It cannot be None.')
        return value
    
    def validate(self, value, try_convert_type=False):
        value = self.is_required(value)
        if value is None: return None
        if try_convert_type: value = self.type_(value)
        return value

    def serialize(self, value : Any) -> str:
        value = self.validate(value)
        if value is None: return None
        return str(value)

    def deserialize(self, value : str) -> Any:
        return self.validate(value, try_convert_type=True)
