import re
from typing import Optional, Pattern, Union
from common.type_checkers.Checkers import chk_boolean, chk_integer, chk_not_none, 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('{}.allow_empty'.format(self.name), allow_empty)
        self._min_length = None if min_length is None else \
            chk_integer('{}.min_length'.format(self.name), min_length, min_value=0)
        self._max_length = None if max_length is None else \
            chk_integer('{}.max_length'.format(self.name), max_length, min_value=self._min_length)
        self._pattern = None if pattern is None else re.compile(pattern)

    def __set__(self, instance, value : str) -> None:
        if self.required: chk_not_none(self.name, value)
        if value is None: super().__set__(instance, value)
        super().__set__(instance, chk_string(
            self.name, value, allow_empty=self._allow_empty, min_length=self._min_length, max_length=self._max_length,
            pattern=self._pattern))
