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)
