# Written by retoor@molodetz.nl

# The script defines a flexible validation and field management system for models, with capabilities for setting attributes, validation, error handling, and JSON conversion. It includes classes for managing various field types with specific properties such as UUID, timestamps for creation and updates, and custom validation rules.

# This script utilizes external Python libraries such as 're' for regex operations, 'uuid' for generating unique identifiers, and 'json' for data interchange. The 'datetime' and 'timezone' modules from the Python standard library are used for date and time operations. 'OrderedDict' from 'collections' provides enhanced dictionary capabilities, and 'copy' allows deep copying of objects.

# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.


import copy
import json
import re
import uuid
from collections import OrderedDict
from datetime import datetime, timezone

TIMESTAMP_REGEX = r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{6}\+\d{2}:\d{2}$"


def now():
    return str(datetime.now(timezone.utc))


def add_attrs(**kwargs):
    def decorator(func):
        for key, value in kwargs.items():
            setattr(func, key, value)
        return func

    return decorator


def validate_attrs(
    required=False, min_length=None, max_length=None, regex=None, **kwargs
):
    def decorator(func):
        return add_attrs(
            required=required,
            min_length=min_length,
            max_length=max_length,
            regex=regex,
            **kwargs,
        )(func)


class Validator:
    _index = 0

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, val):
        self._value = json.loads(json.dumps(val, default=str))

    @property
    def initial_value(self):
        return self.value

    def custom_validation(self):
        return True

    def __init__(
        self,
        required=False,
        min_num=None,
        max_num=None,
        min_length=None,
        max_length=None,
        regex=None,
        value=None,
        kind=None,
        help_text=None,
        app=None,
        model=None,
        **kwargs,
    ):
        self.index = Validator._index
        Validator._index += 1
        self.app = app
        self.model = model
        self.required = required
        self.min_num = min_num
        self.max_num = max_num
        self.min_length = min_length
        self.max_length = max_length
        self.regex = regex
        self._value = None
        self.value = value
        self.kind = kind
        self.help_text = help_text
        self.__dict__.update(kwargs)

    @property
    async def errors(self):
        error_list = []
        if self.value is None and self.required:
            error_list.append("Field is required.")
            return error_list

        if self.value is None:
            return error_list

        if self.kind in [int, float]:
            if self.min_num is not None and self.value < self.min_num:
                error_list.append(f"Field should be minimal {self.min_num}.")
            if self.max_num is not None and self.value > self.max_num:
                error_list.append(f"Field should be maximal {self.max_num}.")
        if self.min_length is not None and len(self.value) < self.min_length:
            error_list.append(
                f"Field should be minimal {self.min_length} characters long."
            )
        if self.max_length is not None and len(self.value) > self.max_length:
            error_list.append(
                f"Field should be maximal {self.max_length} characters long."
            )
        if self.regex and self.value and not re.match(self.regex, self.value):
            error_list.append("Invalid value.")
        if self.kind and not isinstance(self.value, self.kind):
            error_list.append(f"Invalid kind. It is supposed to be {self.kind}.")
        return error_list

    async def validate(self):
        errors = await self.errors
        if errors:
            raise ValueError(f"Errors: {errors}.")
        return True

    @property
    async def is_valid(self):
        try:
            await self.validate()
            return True
        except ValueError:
            return False

    async def to_json(self):
        errors = await self.errors
        is_valid = await self.is_valid
        return {
            "required": self.required,
            "min_num": self.min_num,
            "max_num": self.max_num,
            "min_length": self.min_length,
            "max_length": self.max_length,
            "regex": self.regex,
            "value": self.value,
            "kind": str(self.kind),
            "help_text": self.help_text,
            "errors": errors,
            "is_valid": is_valid,
            "index": self.index,
        }


class ModelField(Validator):

    index = 1

    def __init__(self, name=None, save=True, *args, **kwargs):
        self.name = name
        self.save = save
        super().__init__(*args, **kwargs)

    async def to_json(self):
        result = await super().to_json()
        result["name"] = self.name
        return result


class CreatedField(ModelField):

    @property
    def initial_value(self):
        return now()

    def update(self):
        if not self.value:
            self.value = now()


class UpdatedField(ModelField):

    def update(self):
        self.value = now()


class DeletedField(ModelField):

    def update(self):
        self.value = now()


class UUIDField(ModelField):

    @property
    def value(self):
        return str(self._value)

    @value.setter
    def value(self, val):
        self._value = str(val)

    @property
    def initial_value(self):
        return str(uuid.uuid4())


class BaseModel:

    uid = UUIDField(name="uid", required=True)
    created_at = CreatedField(
        name="created_at",
        required=True,
        regex=TIMESTAMP_REGEX,
        place_holder="Created at",
    )
    updated_at = UpdatedField(
        name="updated_at", regex=TIMESTAMP_REGEX, place_holder="Updated at"
    )
    deleted_at = DeletedField(
        name="deleted_at", regex=TIMESTAMP_REGEX, place_holder="Deleted at"
    )

    @classmethod
    async def from_record(cls, record, mapper):
        model = cls()
        model.mapper = mapper
        model.record = record
        return model

    @property
    def mapper(self):
        return self._mapper

    @mapper.setter
    def mapper(self, value):
        self._mapper = value

    @property
    def record(self):
        return {key: field.value for key, field in self.fields.items()}

    @record.setter
    def record(self, val):
        for key, value in val.items():
            field = self.fields.get(key)
            if not field:
                continue
            self[key] = value
        return self

    def __init__(self, *args, **kwargs):
        self._mapper = None
        self.fields = {}
        for key in dir(self.__class__):
            obj = getattr(self.__class__, key)

            if isinstance(obj, Validator):
                self.__dict__[key] = copy.deepcopy(obj)
                self.__dict__[key].value = kwargs.pop(
                    key, self.__dict__[key].initial_value
                )
                self.fields[key] = self.__dict__[key]
                self.fields[key].model = self
                self.fields[key].app = kwargs.get("app")

    def __setitem__(self, key, value):
        obj = self.__dict__.get(key)
        if isinstance(obj, Validator):
            obj.value = value

    def __getattr__(self, key):
        obj = self.__dict__.get(key)
        if isinstance(obj, Validator):
            return obj.value
        return obj

    def set_user_data(self, data):
        for key, value in data.items():
            field = self.fields.get(key)
            if not field:
                continue
            if value.get("name"):
                value = value.get("value")
            field.value = value

    @property
    async def is_valid(self):
        return all([await field.is_valid for field in self.fields.values()])

    def __getitem__(self, key):
        obj = self.__dict__.get(key)
        if isinstance(obj, Validator):
            return obj.value

    def __setattr__(self, key, value):
        obj = getattr(self, key)
        if isinstance(obj, Validator):
            obj.value = value
        else:
            self.__dict__[key] = value

    @property
    async def recordz(self):
        obj = await self.to_json()
        record = {}
        for key, value in obj.items():
            if not isinstance(value, dict) or "value" not in value:
                continue
            if getattr(self, key).save:
                record[key] = value.get("value")
        return record

    async def to_json(self, encode=False):
        model_data = OrderedDict(
            {
                "uid": self.uid.value,
                "created_at": self.created_at.value,
                "updated_at": self.updated_at.value,
                "deleted_at": self.deleted_at.value,
                "is_valid": await self.is_valid,
            }
        )

        for key, value in self.fields.items():
            if key == "record":
                continue
            value = self.__dict__[key]
            if hasattr(value, "value"):
                model_data[key] = await value.to_json()
        if encode:
            return json.dumps(model_data, indent=2)
        return model_data


class FormElement(ModelField):

    def __init__(self, place_holder=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.place_holder = place_holder


class FormElement(ModelField):

    def __init__(self, place_holder=None, *args, **kwargs):
        self.place_holder = place_holder
        super().__init__(*args, **kwargs)

    async def to_json(self):
        data = await super().to_json()
        data["name"] = self.name
        data["place_holder"] = self.place_holder
        return data
