from parallels.plesk.hosting_description.validate.validators.base import ValidatorBase
from parallels.plesk import messages


class ValidatorSelector(ValidatorBase):
    """Check that specified document conforms to one of specified validators

    Examples could be:
    - validate that document is a string or a list of strings,
    - validate that document is a dictionary or a list
    """

    def __init__(self, items):
        """
        :type items: list[parallels.plesk.hosting_description.validate.validators.base.ValidatorBase]
        :return:
        """
        self._items = items

    def validate(self, document, context=None):
        """Validate specified document (variable) according to current validator's rules

        Return list of found issues.

        :rtype: list[unicode]
        """
        matched_type_errors = None
        for item in self._items:
            errors = item.validate(document, context)
            if len(errors) == 0:
                return []
            if item.match_type(document):
                matched_type_errors = errors

        if matched_type_errors is not None:
            return matched_type_errors
        else:
            return [self._format_error(messages.VALIDATOR_INVALID_DATA, context)]

    @property
    def items(self):
        """
        :rtype: list[parallels.plesk.hosting_description.validate.validators.base.ValidatorBase]
        """
        return self._items

    def __repr__(self):
        return 'ValidatorSelector(%r)' % (self._items,)

    def __eq__(self, other):
        return isinstance(other, ValidatorSelector) and other.items == self.items
