# 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 re
from typing import Optional, Pattern, Union
from common.type_checkers.Checkers import chk_boolean, chk_integer, chk_string
from .Field import Field

class StringField(Field):
    def __init__(
        self, *args, allow_empty : bool = False, min_length : Optional[int] = None, max_length : Optional[int] = None,
        pattern : Optional[Union[Pattern, str]] = None, **kwargs) -> None:

        super().__init__(*args, type_=str, **kwargs)
        self._allow_empty = chk_boolean('StringField.allow_empty', allow_empty)
        self._min_length = None if min_length is None else \
            chk_integer('StringField.min_length', min_length, min_value=0)
        self._max_length = None if max_length is None else \
            chk_integer('StringField.max_length', max_length, min_value=self._min_length)
        self._pattern = None if pattern is None else re.compile(pattern)

    def validate(self, value : str, try_convert_type=False) -> str:
        value = super().validate(value, try_convert_type=try_convert_type)
        if value is None: return None
        return chk_string(
            self.name, value, allow_empty=self._allow_empty, min_length=self._min_length, max_length=self._max_length,
            pattern=self._pattern)
