#
# Copyright (c), 2016-2020, SISSA (International School for Advanced Studies).
# All rights reserved.
# This file is distributed under the terms of the MIT License.
# See the file 'LICENSE' in the root directory of the present
# distribution, or http://opensource.org/licenses/MIT.
#
# @author Davide Brunato <brunato@sissa.it>
#
"""
This module contains XMLSchema classes creator for xmlschema package.

Two schema classes are created at the end of this module, XMLSchema10 for XSD 1.0 and
XMLSchema11 for XSD 1.1. The latter class parses also XSD 1.0 schemas, as prescribed by
the standard.
"""
import sys
if sys.version_info < (3, 7):
    from typing import GenericMeta as ABCMeta
else:
    from abc import ABCMeta

import os
import logging
import threading
import warnings
import re
import sys
from copy import copy
from itertools import chain
from typing import cast, Callable, ItemsView, List, Optional, Dict, Any, \
    Set, Union, Tuple, Type, Iterator, Counter

from elementpath import XPathToken

from ..exceptions import XMLSchemaTypeError, XMLSchemaKeyError, XMLSchemaRuntimeError, \
    XMLSchemaValueError, XMLSchemaNamespaceError
from ..names import VC_MIN_VERSION, VC_MAX_VERSION, VC_TYPE_AVAILABLE, \
    VC_TYPE_UNAVAILABLE, VC_FACET_AVAILABLE, VC_FACET_UNAVAILABLE, XSD_NOTATION, \
    XSD_ATTRIBUTE, XSD_ATTRIBUTE_GROUP, XSD_GROUP, XSD_SIMPLE_TYPE, XSI_TYPE, \
    XSD_COMPLEX_TYPE, XSD_ELEMENT, XSD_SEQUENCE, XSD_CHOICE, XSD_ALL, XSD_ANY, \
    XSD_ANY_ATTRIBUTE, XSD_ANY_TYPE, XSD_NAMESPACE, XML_NAMESPACE, XSI_NAMESPACE, \
    VC_NAMESPACE, SCHEMAS_DIR, LOCATION_HINTS, XSD_ANNOTATION, XSD_INCLUDE, \
    XSD_IMPORT, XSD_REDEFINE, XSD_OVERRIDE, XSD_DEFAULT_OPEN_CONTENT, \
    XSD_ANY_SIMPLE_TYPE, XSD_UNION, XSD_LIST, XSD_RESTRICTION
from ..etree import etree_element, ParseError
from ..aliases import ElementType, XMLSourceType, NamespacesType, LocationsType, \
    SchemaType, SchemaSourceType, ConverterType, ComponentClassType, DecodeType, \
    EncodeType, BaseXsdType, AtomicValueType, ExtraValidatorType, SchemaGlobalType
from ..helpers import prune_etree, get_namespace, get_qname
from ..namespaces import NamespaceResourcesMap, NamespaceView
from ..resources import is_local_url, is_remote_url, url_path_is_file, \
    normalize_locations, fetch_resource, normalize_url, XMLResource
from ..converters import XMLSchemaConverter
from ..xpath import XMLSchemaProtocol, XMLSchemaProxy, ElementPathMixin
from .. import dataobjects

from .exceptions import XMLSchemaParseError, XMLSchemaValidationError, XMLSchemaEncodeError, \
    XMLSchemaNotBuiltError, XMLSchemaIncludeWarning, XMLSchemaImportWarning
from .helpers import get_xsd_derivation_attribute
from .xsdbase import check_validation_mode, XsdValidator, XsdComponent, XsdAnnotation
from .notations import XsdNotation
from .identities import XsdIdentity, XsdKey, XsdKeyref, XsdUnique, \
    Xsd11Key, Xsd11Unique, Xsd11Keyref, IdentityCounter, KeyrefCounter, IdentityMapType
from .facets import XSD_10_FACETS, XSD_11_FACETS
from .simple_types import XsdSimpleType, XsdList, XsdUnion, XsdAtomicRestriction, \
    Xsd11AtomicRestriction, Xsd11Union
from .attributes import XsdAttribute, XsdAttributeGroup, Xsd11Attribute
from .complex_types import XsdComplexType, Xsd11ComplexType
from .groups import XsdGroup, Xsd11Group
from .elements import XsdElement, Xsd11Element
from .wildcards import XsdAnyElement, XsdAnyAttribute, Xsd11AnyElement, \
    Xsd11AnyAttribute, XsdDefaultOpenContent
from .global_maps import XsdGlobals

logger = logging.getLogger('xmlschema')

XSD_VERSION_PATTERN = re.compile(r'^\d+\.\d+$')
DRIVE_PATTERN = re.compile(r'^[a-zA-Z]:$')

# Elements for building dummy groups
ATTRIBUTE_GROUP_ELEMENT = etree_element(XSD_ATTRIBUTE_GROUP)
ANY_ATTRIBUTE_ELEMENT = etree_element(
    XSD_ANY_ATTRIBUTE, attrib={'namespace': '##any', 'processContents': 'lax'}
)
SEQUENCE_ELEMENT = etree_element(XSD_SEQUENCE)
ANY_ELEMENT = etree_element(
    XSD_ANY,
    attrib={
        'namespace': '##any',
        'processContents': 'lax',
        'minOccurs': '0',
        'maxOccurs': 'unbounded'
    })

GLOBAL_TAGS = frozenset((XSD_NOTATION, XSD_SIMPLE_TYPE, XSD_COMPLEX_TYPE,
                         XSD_ATTRIBUTE, XSD_ATTRIBUTE_GROUP, XSD_GROUP, XSD_ELEMENT))


class XMLSchemaMeta(ABCMeta):
    XSD_VERSION: str
    create_meta_schema: Callable[['XMLSchemaMeta', Optional[str]], SchemaType]

    def __new__(mcs, name: str, bases: Tuple[Type[Any], ...], dict_: Dict[str, Any]) \
            -> 'XMLSchemaMeta':
        assert bases, "a base class is mandatory"
        base_class = bases[0]

        # For backward compatibility (will be removed in v2.0)
        if 'BUILDERS' in dict_:
            msg = "'BUILDERS' will be removed in v2.0, provide the appropriate " \
                  "attributes instead (eg. xsd_element_class = Xsd11Element)"
            warnings.warn(msg, DeprecationWarning, stacklevel=1)

            for k, v in dict_['BUILDERS'].items():
                if k == 'simple_type_factory':
                    dict_['simple_type_factory'] = staticmethod(v)
                    continue

                attr_name = 'xsd_{}'.format(k)
                if not hasattr(base_class, attr_name):
                    continue
                elif getattr(base_class, attr_name) is not v:
                    dict_[attr_name] = v

        if isinstance(dict_.get('meta_schema'), str):
            # Build a new meta-schema class and register it into module's globals
            meta_schema_file: str = dict_.pop('meta_schema')
            meta_schema_class_name = 'Meta' + name

            meta_schema: Optional[SchemaType]
            meta_schema = getattr(base_class, 'meta_schema', None)
            if meta_schema is None:
                meta_bases = bases
            else:
                # Use base's meta_schema class as base for the new meta-schema
                meta_bases = (meta_schema.__class__,)
                if len(bases) > 1:
                    meta_bases += bases[1:]

            meta_schema_class = super(XMLSchemaMeta, mcs).__new__(
                mcs, meta_schema_class_name, meta_bases, dict_
            )
            meta_schema_class.__qualname__ = meta_schema_class_name
            module = sys.modules[dict_['__module__']]
            setattr(module, meta_schema_class_name, meta_schema_class)

            meta_schema = meta_schema_class.create_meta_schema(meta_schema_file)
            dict_['meta_schema'] = meta_schema

        # Create the class and check some basic attributes
        cls = super(XMLSchemaMeta, mcs).__new__(mcs, name, bases, dict_)
        if cls.XSD_VERSION not in ('1.0', '1.1'):
            raise XMLSchemaValueError("XSD_VERSION must be '1.0' or '1.1'")
        return cls


class XMLSchemaBase(XsdValidator, ElementPathMixin[Union[SchemaType, XsdElement]],
                    metaclass=XMLSchemaMeta):
    """
    Base class for an XML Schema instance.

    :param source: an URI that reference to a resource or a file path or a file-like \
    object or a string containing the schema or an Element or an ElementTree document \
    or an :class:`XMLResource` instance. A multi source initialization is supported \
    providing a not empty list of XSD sources.
    :param namespace: is an optional argument that contains the URI of the namespace \
    that has to used in case the schema has no namespace (chameleon schema). For other \
    cases, when specified, it must be equal to the *targetNamespace* of the schema.
    :param validation: the XSD validation mode to use for build the schema, \
    that can be 'strict' (default), 'lax' or 'skip'.
    :param global_maps: is an optional argument containing an :class:`XsdGlobals` \
    instance, a mediator object for sharing declaration data between dependents \
    schema instances.
    :param converter: is an optional argument that can be an :class:`XMLSchemaConverter` \
    subclass or instance, used for defining the default XML data converter for XML Schema instance.
    :param locations: schema extra location hints, that can include custom resource locations \
    (eg. local XSD file instead of remote resource) or additional namespaces to import after \
    processing schema's import statements. Can be a dictionary or a sequence of couples \
    (namespace URI, resource URL). Extra locations passed using a tuple container are not \
    normalized.
    :param base_url: is an optional base URL, used for the normalization of relative paths \
    when the URL of the schema resource can't be obtained from the source argument.
    :param allow: defines the security mode for accessing resource locations. Can be \
    'all', 'remote', 'local' or 'sandbox'. Default is 'all' that means all types of \
    URLs are allowed. With 'remote' only remote resource URLs are allowed. With 'local' \
    only file paths and URLs are allowed. With 'sandbox' only file paths and URLs that \
    are under the directory path identified by source or by the *base_url* argument \
    are allowed.
    :param defuse: defines when to defuse XML data using a `SafeXMLParser`. Can be \
    'always', 'remote' or 'never'. For default defuses only remote XML data.
    :param timeout: the timeout in seconds for fetching resources. Default is `300`.
    :param build: defines whether build the schema maps. Default is `True`.
    :param use_meta: if `True` the schema processor uses the validator meta-schema, \
    otherwise a new meta-schema is added at the end. In the latter case the meta-schema \
    is rebuilt if any base namespace has been overridden by an import. Ignored if the \
    argument *global_maps* is provided.
    :param use_fallback: if `True` the schema processor uses the validator fallback \
    location hints to load well-known namespaces (eg. xhtml).
    :param loglevel: for setting a different logging level for schema initialization \
    and building. For default is WARNING (30). For INFO level set it with 20, for \
    DEBUG level with 10. The default loglevel is restored after schema building, \
    when exiting the initialization method.

    :cvar XSD_VERSION: store the XSD version (1.0 or 1.1).
    :cvar BASE_SCHEMAS: a dictionary from namespace to schema resource for meta-schema bases.
    :cvar fallback_locations: fallback schema location hints for other standard namespaces.
    :cvar meta_schema: the XSD meta-schema instance.
    :cvar attribute_form_default: the schema's *attributeFormDefault* attribute. \
    Default is 'unqualified'.
    :cvar element_form_default: the schema's *elementFormDefault* attribute. \
    Default is 'unqualified'.
    :cvar block_default: the schema's *blockDefault* attribute. Default is ''.
    :cvar final_default: the schema's *finalDefault* attribute. Default is ''.
    :cvar default_attributes: the XSD 1.1 schema's *defaultAttributes* attribute. \
    Default is ``None``.
    :cvar xpath_tokens: symbol table for schema bound XPath 2.0 parsers. Initially set to \
    ``None`` it's redefined at instance level with a dictionary at first use of the XPath \
    selector. The parser symbol table is extended with schema types constructors.

    :ivar target_namespace: is the *targetNamespace* of the schema, the namespace to which \
    belong the declarations/definitions of the schema. If it's empty no namespace is associated \
    with the schema. In this case the schema declarations can be reused from other namespaces as \
    *chameleon* definitions.
    :ivar validation: validation mode, can be 'strict', 'lax' or 'skip'.
    :ivar maps: XSD global declarations/definitions maps. This is an instance of \
    :class:`XsdGlobal`, that stores the *global_maps* argument or a new object \
    when this argument is not provided.
    :ivar converter: the default converter used for XML data decoding/encoding.
    :ivar locations: schema location hints.
    :ivar namespaces: a dictionary that maps from the prefixes used by the schema \
    into namespace URI.
    :ivar imports: a dictionary of namespace imports of the schema, that maps namespace \
    URI to imported schema object, or `None` in case of unsuccessful import.
    :ivar includes: a dictionary of included schemas, that maps a schema location to an \
    included schema. It also comprehend schemas included by "xs:redefine" or \
    "xs:override" statements.
    :ivar warnings: warning messages about failure of import and include elements.

    :ivar notations: `xsd:notation` declarations.
    :vartype notations: NamespaceView
    :ivar types: `xsd:simpleType` and `xsd:complexType` global declarations.
    :vartype types: NamespaceView
    :ivar attributes: `xsd:attribute` global declarations.
    :vartype attributes: NamespaceView
    :ivar attribute_groups: `xsd:attributeGroup` definitions.
    :vartype attribute_groups: NamespaceView
    :ivar groups: `xsd:group` global definitions.
    :vartype groups: NamespaceView
    :ivar elements: `xsd:element` global declarations.
    :vartype elements: NamespaceView
    """
    # Instance attributes annotations
    source: XMLResource
    namespaces: NamespacesType
    converter: Union[ConverterType]
    locations: NamespaceResourcesMap
    maps: XsdGlobals
    imports: Dict[str, Optional[SchemaType]]
    includes: Dict[str, SchemaType]
    warnings: List[str]

    notations: NamespaceView[XsdNotation]
    types: NamespaceView[BaseXsdType]
    attributes: NamespaceView[XsdAttribute]
    attribute_groups: NamespaceView[XsdAttributeGroup]
    groups: NamespaceView[XsdGroup]
    elements: NamespaceView[XsdElement]
    substitution_groups: NamespaceView[List[XsdElement]]
    identities: NamespaceView[XsdIdentity]

    XSD_VERSION: str = '1.0'
    meta_schema: Optional['XMLSchemaBase'] = None
    BASE_SCHEMAS: Dict[str, str] = {}
    fallback_locations: Dict[str, str] = LOCATION_HINTS.copy()
    _locations: Tuple[Tuple[str, str], ...] = ()
    _annotations = None

    # XSD components classes
    xsd_notation_class = XsdNotation
    xsd_complex_type_class = XsdComplexType
    xsd_attribute_class = XsdAttribute
    xsd_any_attribute_class = XsdAnyAttribute
    xsd_attribute_group_class = XsdAttributeGroup
    xsd_group_class = XsdGroup
    xsd_element_class = XsdElement
    xsd_any_class = XsdAnyElement
    xsd_atomic_restriction_class = XsdAtomicRestriction
    xsd_list_class = XsdList
    xsd_union_class = XsdUnion
    xsd_key_class = XsdKey
    xsd_keyref_class = XsdKeyref
    xsd_unique_class = XsdUnique

    # Schema defaults
    target_namespace = ''
    attribute_form_default = 'unqualified'
    element_form_default = 'unqualified'
    block_default = ''
    final_default = ''
    redefine = None

    # Additional defaults for XSD 1.1
    default_attributes: Optional[Union[str, XsdAttributeGroup]] = None
    default_open_content = None
    override = None

    # Store XPath constructors tokens (for schema and its assertions)
    xpath_tokens: Optional[Dict[str, Type[XPathToken]]] = None

    def __init__(self, source: Union[SchemaSourceType, List[SchemaSourceType]],
                 namespace: Optional[str] = None,
                 validation: str = 'strict',
                 global_maps: Optional[XsdGlobals] = None,
                 converter: Optional[ConverterType] = None,
                 locations: Optional[LocationsType] = None,
                 base_url: Optional[str] = None,
                 allow: str = 'all',
                 defuse: str = 'remote',
                 timeout: int = 300,
                 build: bool = True,
                 use_meta: bool = True,
                 use_fallback: bool = True,
                 loglevel: Optional[Union[str, int]] = None) -> None:

        super(XMLSchemaBase, self).__init__(validation)
        self.lock = threading.Lock()  # Lock for build operations

        if loglevel is not None:
            if isinstance(loglevel, str):
                level = loglevel.strip().upper()
                if level not in {'DEBUG', 'INFO', 'WARN', 'WARNING', 'ERROR', 'CRITICAL'}:
                    raise XMLSchemaValueError("{!r} is not a valid loglevel".format(loglevel))
                logger.setLevel(getattr(logging, level))
            else:
                logger.setLevel(loglevel)
        elif build and global_maps is None:
            logger.setLevel(logging.WARNING)

        if allow == 'sandbox' and base_url is None and is_local_url(source):
            # Allow sandbox mode without a base_url using the initial schema URL as base
            assert isinstance(source, str)
            base_url = os.path.dirname(normalize_url(source))

        other_sources: List[SchemaSourceType]
        if isinstance(source, list):
            if not source:
                raise XMLSchemaValueError("no XSD source provided!")
            other_sources = source[1:]
            source = source[0]
        else:
            other_sources = []

        if isinstance(source, XMLResource):
            self.source = source
        else:
            self.source = XMLResource(source, base_url, allow, defuse, timeout)

        logger.debug("Read schema from %r", self.source.url or self.source.source)

        self.imports = {}
        self.includes = {}
        self.warnings = []
        self._root_elements = None  # type: Optional[Set[str]]

        self.name = self.source.name
        root = self.source.root

        # Initialize schema's namespaces, the XML namespace is implicitly declared.
        self.namespaces = self.source.get_namespaces({'xml': XML_NAMESPACE}, root_only=True)

        if 'targetNamespace' in root.attrib:
            self.target_namespace = root.attrib['targetNamespace'].strip()
            if not self.target_namespace:
                # https://www.w3.org/TR/2004/REC-xmlschema-1-20041028/structures.html#element-schema
                self.parse_error("the attribute 'targetNamespace' cannot be an empty string", root)
            elif namespace is not None and self.target_namespace != namespace:
                msg = "wrong namespace (%r instead of %r) for XSD resource %s"
                self.parse_error(msg % (self.target_namespace, namespace, self.url), root)

        if not self.target_namespace and namespace is not None:
            # Chameleon schema case
            self.target_namespace = namespace
            if '' not in self.namespaces:
                self.namespaces[''] = namespace

        elif '' not in self.namespaces:
            # If not declared map the default namespace to no namespace
            self.namespaces[''] = ''

        logger.debug("Schema targetNamespace is %r", self.target_namespace)
        logger.debug("Declared namespaces: %r", self.namespaces)

        # Parses the schema defaults
        if 'attributeFormDefault' in root.attrib:
            self.attribute_form_default = root.attrib['attributeFormDefault']

        if 'elementFormDefault' in root.attrib:
            self.element_form_default = root.attrib['elementFormDefault']

        if 'blockDefault' in root.attrib:
            if self.meta_schema is None:
                pass  # Skip for XSD 1.0 meta-schema that has blockDefault="#all"
            else:
                try:
                    self.block_default = get_xsd_derivation_attribute(
                        root, 'blockDefault', {'extension', 'restriction', 'substitution'}
                    )
                except ValueError as err:
                    self.parse_error(err, root)

        if 'finalDefault' in root.attrib:
            try:
                self.final_default = get_xsd_derivation_attribute(root, 'finalDefault')
            except ValueError as err:
                self.parse_error(err, root)

        if converter is None:
            self.converter = XMLSchemaConverter
        else:
            self.converter = self.get_converter(converter)

        if self.meta_schema is None:
            self.locations = NamespaceResourcesMap()

            # Meta-schema maps creation (MetaXMLSchema10/11 classes)
            self.maps = global_maps or XsdGlobals(self)
            for child in self.source.root:
                if child.tag == XSD_OVERRIDE:
                    self.include_schema(child.attrib['schemaLocation'], self.base_url)
            return  # Meta-schemas don't need to be checked and don't process imports

        # Completes the namespaces map with internal declarations, remapping same prefixes.
        self.namespaces = self.source.get_namespaces(self.namespaces)

        if locations:
            if isinstance(locations, tuple):
                self._locations = locations
            else:
                self._locations = tuple(normalize_locations(locations, self.base_url))

        self.locations = NamespaceResourcesMap(self.source.get_locations(self._locations))
        if not use_fallback:
            self.fallback_locations = {}

        with self.meta_schema.lock:
            if not self.meta_schema.maps.types:
                self.meta_schema.maps.build()

        # Create or set the XSD global maps instance
        if isinstance(global_maps, XsdGlobals):
            self.maps = global_maps
        elif global_maps is not None:
            raise XMLSchemaTypeError("'global_maps' argument must be an %r instance" % XsdGlobals)
        elif use_meta and self.target_namespace not in self.meta_schema.maps.namespaces:
            self.maps = self.meta_schema.maps.copy(self, validation)
        else:
            self.maps = XsdGlobals(self, validation)

        if any(ns == VC_NAMESPACE for ns in self.namespaces.values()):
            # For XSD 1.1+ apply versioning filter to schema tree. See the paragraph
            # 4.2.2 of XSD 1.1 (Part 1: Structures) definition for details.
            # Ref: https://www.w3.org/TR/xmlschema11-1/#cip
            if prune_etree(root, selector=lambda x: not self.version_check(x)):
                for k in list(root.attrib):
                    if k not in {'targetNamespace', VC_MIN_VERSION, VC_MAX_VERSION}:
                        del root.attrib[k]

        # Validate the schema document (transforming validation errors to parse errors)
        if validation != 'skip':
            for e in self.meta_schema.iter_errors(root, namespaces=self.namespaces):
                self.parse_error(e.reason or e, elem=e.elem)

        self._parse_inclusions()
        self._parse_imports()

        # Imports by argument (usually from xsi:schemaLocation attribute).
        for ns in self.locations:
            if ns not in self.maps.namespaces:
                self._import_namespace(ns, self.locations[ns])

        # XSD 1.1 default declarations (defaultAttributes, defaultOpenContent,
        # xpathDefaultNamespace)
        if self.XSD_VERSION > '1.0':
            self.xpath_default_namespace = self._parse_xpath_default_namespace(root)
            if 'defaultAttributes' in root.attrib:
                try:
                    self.default_attributes = self.resolve_qname(root.attrib['defaultAttributes'])
                except (ValueError, KeyError, RuntimeError) as err:
                    self.parse_error(err, root)

            for child in root:
                if child.tag == XSD_DEFAULT_OPEN_CONTENT:
                    self.default_open_content = XsdDefaultOpenContent(child, self)
                    break

        _source: Union[SchemaSourceType, XMLResource]
        for _source in other_sources:
            if not isinstance(_source, XMLResource):
                _source = XMLResource(_source, base_url, allow, defuse, timeout)

            if not _source.root.get('targetNamespace') and self.target_namespace:
                # Adding a chameleon schema: set the namespace with targetNamespace
                self.add_schema(_source, namespace=self.target_namespace)
            else:
                self.add_schema(_source)

        try:
            if build:
                self.maps.build()
        finally:
            if loglevel is not None:
                logger.setLevel(logging.WARNING)  # Restore default logging

    def __getstate__(self) -> Dict[str, Any]:
        state = self.__dict__.copy()
        state.pop('lock', None)
        state.pop('xpath_tokens', None)
        return state

    def __setstate__(self, state: Dict[str, Any]) -> None:
        self.__dict__.update(state)
        self.lock = threading.Lock()

    def __repr__(self) -> str:
        if self.url:
            return '%s(name=%r, namespace=%r)' % (
                self.__class__.__name__, self.name, self.target_namespace
            )
        return '%s(namespace=%r)' % (self.__class__.__name__, self.target_namespace)

    def __setattr__(self, name: str, value: Any) -> None:
        if name == 'maps':
            if self.meta_schema is None and hasattr(self, 'maps'):
                msg = "cannot change the global maps instance of a meta-schema"
                raise XMLSchemaValueError(msg)

            super(XMLSchemaBase, self).__setattr__(name, value)
            self.notations = NamespaceView(value.notations, self.target_namespace)
            self.types = NamespaceView(value.types, self.target_namespace)
            self.attributes = NamespaceView(value.attributes, self.target_namespace)
            self.attribute_groups = NamespaceView(value.attribute_groups,
                                                  self.target_namespace)
            self.groups = NamespaceView(value.groups, self.target_namespace)
            self.elements = NamespaceView(value.elements, self.target_namespace)
            self.substitution_groups = NamespaceView(value.substitution_groups,
                                                     self.target_namespace)
            self.identities = NamespaceView(value.identities, self.target_namespace)
            value.register(self)
        else:
            if name == 'validation':
                check_validation_mode(value)
            super(XMLSchemaBase, self).__setattr__(name, value)

    def __iter__(self) -> Iterator[XsdElement]:
        yield from sorted(self.elements.values(), key=lambda x: x.name)

    def __reversed__(self) -> Iterator[XsdElement]:
        yield from sorted(self.elements.values(), key=lambda x: x.name, reverse=True)

    def __len__(self) -> int:
        return len(self.elements)

    @property
    def xpath_proxy(self) -> XMLSchemaProxy:
        return XMLSchemaProxy(cast(XMLSchemaProtocol, self))

    @property
    def xsd_version(self) -> str:
        """Compatibility property that returns the class attribute XSD_VERSION."""
        return self.XSD_VERSION

    # XML resource attributes access
    @property
    def root(self) -> ElementType:
        """Root element of the schema."""
        return self.source.root

    def get_text(self) -> str:
        """Returns the source text of the XSD schema."""
        return self.source.get_text()

    @property
    def url(self) -> Optional[str]:
        """Schema resource URL, is `None` if the schema is built from an Element or a string."""
        return self.source.url

    @property
    def base_url(self) -> Optional[str]:
        """The base URL of the source of the schema."""
        return self.source.base_url

    @property
    def filepath(self) -> Optional[str]:
        """The filepath if the schema is loaded from a local XSD file, `None` otherwise."""
        return self.source.filepath

    @property
    def allow(self) -> str:
        """Defines the resource access security mode, can be 'all', 'local' or 'sandbox'."""
        return self.source.allow

    @property
    def defuse(self) -> str:
        """Defines when to defuse XML data, can be 'always', 'remote' or 'never'."""
        return self.source.defuse

    @property
    def timeout(self) -> int:
        """Timeout in seconds for fetching resources."""
        return self.source.timeout

    @property
    def use_meta(self) -> bool:
        """Returns `True` if the class meta-schema is used."""
        return self.meta_schema is self.__class__.meta_schema

    # Schema root attributes
    @property
    def tag(self) -> str:
        """Schema root tag. For compatibility with the ElementTree API."""
        return self.source.root.tag

    @property
    def id(self) -> Optional[str]:
        """The schema's *id* attribute, defaults to ``None``."""
        return self.source.root.get('id')

    @property
    def version(self) -> Optional[str]:
        """The schema's *version* attribute, defaults to ``None``."""
        return self.source.root.get('version')

    @property
    def schema_location(self) -> List[Tuple[str, str]]:
        """
        A list of location hints extracted from the *xsi:schemaLocation* attribute of the schema.
        """
        return [(k, v) for k, v in self.source.iter_location_hints() if k]

    @property
    def no_namespace_schema_location(self) -> Optional[str]:
        """
        A location hint extracted from the *xsi:noNamespaceSchemaLocation* attribute of the schema.
        """
        for k, v in self.source.iter_location_hints():
            if not k:
                return v
        return None

    @property
    def default_namespace(self) -> Optional[str]:
        """The namespace associated to the empty prefix ''."""
        return self.namespaces.get('')

    @property
    def target_prefix(self) -> str:
        """The prefix associated to the *targetNamespace*."""
        for prefix, namespace in self.namespaces.items():
            if namespace == self.target_namespace:
                return prefix
        return ''

    @classmethod
    def builtin_types(cls) -> NamespaceView[BaseXsdType]:
        """Returns the XSD built-in types of the meta-schema."""
        if cls.meta_schema is None:
            raise XMLSchemaRuntimeError("meta-schema unavailable for %r" % cls)

        try:
            meta_schema: SchemaType = cls.meta_schema.maps.namespaces[XSD_NAMESPACE][0]
            builtin_types = meta_schema.types
        except KeyError:
            raise XMLSchemaNotBuiltError(cls.meta_schema, "missing XSD namespace in meta-schema")
        else:
            if not builtin_types:
                cls.meta_schema.build()
            return builtin_types

    @property
    def annotations(self) -> List[XsdAnnotation]:
        if self._annotations is None:
            self._annotations = [
                XsdAnnotation(child, self) for child in self.source.root
                if child.tag == XSD_ANNOTATION
            ]
        return self._annotations

    @property
    def root_elements(self) -> List[XsdElement]:
        """
        The list of global elements that are not used by reference in any model of the schema.
        This is implemented as lazy property because it's computationally expensive to build
        when the schema model is complex.
        """
        if not self.elements:
            return []
        elif len(self.elements) == 1:
            return list(self.elements.values())
        elif self._root_elements is None:
            names = set(e.name for e in self.elements.values())
            for xsd_element in self.elements.values():
                for e in xsd_element.iter():
                    if e is xsd_element or isinstance(e, XsdAnyElement):
                        continue
                    elif e.ref or e.parent is None:
                        if e.name in names:
                            names.discard(e.name)
                            if not names:
                                break
            self._root_elements = set(names)

        assert self._root_elements is not None
        return [e for e in self.elements.values() if e.name in self._root_elements]

    @property
    def simple_types(self) -> List[XsdSimpleType]:
        """Returns a list containing the global simple types."""
        return [x for x in self.types.values() if isinstance(x, XsdSimpleType)]

    @property
    def complex_types(self) -> List[XsdComplexType]:
        """Returns a list containing the global complex types."""
        return [x for x in self.types.values() if isinstance(x, XsdComplexType)]

    @classmethod
    def create_meta_schema(cls, source: Optional[str] = None,
                           base_schemas: Union[None, Dict[str, str],
                                               List[Tuple[str, str]]] = None,
                           global_maps: Optional[XsdGlobals] = None) -> SchemaType:
        """
        Creates a new meta-schema instance.

        :param source: an optional argument referencing to or containing the XSD meta-schema \
        resource. Required if the schema class doesn't already have a meta-schema.
        :param base_schemas: an optional dictionary that contains namespace URIs and \
        schema locations. If provided is used as substitute for class BASE_SCHEMAS. \
        Also a sequence of (namespace, location) items can be provided if there are more \
        schema documents for one or more namespaces.
        :param global_maps: is an optional argument containing an :class:`XsdGlobals` \
        instance for the new meta schema. If not provided a new map is created.
        """
        if source is None:
            if cls.meta_schema is None or cls.meta_schema.url:
                raise XMLSchemaValueError("Missing meta-schema source URL")
            source = cast(str, cls.meta_schema.url)

        _base_schemas: Union[ItemsView[str, str], List[Tuple[str, str]]]
        if base_schemas is None:
            _base_schemas = cls.BASE_SCHEMAS.items()
        elif isinstance(base_schemas, dict):
            _base_schemas = base_schemas.items()
        else:
            try:
                _base_schemas = [(n, l) for n, l in base_schemas]
            except ValueError:
                raise ValueError(
                    "The argument 'base_schemas' is not a dictionary nor a sequence of items"
                )

        meta_schema: SchemaType
        meta_schema_class = cls if cls.meta_schema is None else cls.meta_schema.__class__
        meta_schema = meta_schema_class(source, XSD_NAMESPACE, global_maps=global_maps,
                                        defuse='never', build=False)
        for ns, location in _base_schemas:
            if ns == XSD_NAMESPACE:
                meta_schema.include_schema(location=location)
            else:
                meta_schema.import_schema(namespace=ns, location=location)
        return meta_schema

    def simple_type_factory(self, elem: ElementType,
                            schema: Optional[SchemaType] = None,
                            parent: Optional[XsdComponent] = None) -> XsdSimpleType:
        """
        Factory function for XSD simple types. Parses the xs:simpleType element and its
        child component, that can be a restriction, a list or an union. Annotations are
        linked to simple type instance, omitting the inner annotation if both are given.
        """
        if schema is None:
            schema = self

        annotation = None
        try:
            child = elem[0]
        except IndexError:
            return cast(XsdSimpleType, self.maps.types[XSD_ANY_SIMPLE_TYPE])
        else:
            if child.tag == XSD_ANNOTATION:
                annotation = XsdAnnotation(child, schema, parent)
                try:
                    child = elem[1]
                except IndexError:
                    schema.parse_error("(restriction | list | union) expected", elem)
                    return cast(XsdSimpleType, self.maps.types[XSD_ANY_SIMPLE_TYPE])

        xsd_type: XsdSimpleType
        if child.tag == XSD_RESTRICTION:
            xsd_type = self.xsd_atomic_restriction_class(child, schema, parent)
        elif child.tag == XSD_LIST:
            xsd_type = self.xsd_list_class(child, schema, parent)
        elif child.tag == XSD_UNION:
            xsd_type = self.xsd_union_class(child, schema, parent)
        else:
            schema.parse_error("(restriction | list | union) expected", elem)
            return cast(XsdSimpleType, self.maps.types[XSD_ANY_SIMPLE_TYPE])

        if annotation is not None:
            xsd_type._annotation = annotation

        try:
            xsd_type.name = get_qname(schema.target_namespace, elem.attrib['name'])
        except KeyError:
            if parent is None:
                schema.parse_error("missing attribute 'name' in a global simpleType", elem)
                xsd_type.name = 'nameless_%s' % str(id(xsd_type))
        else:
            if parent is not None:
                schema.parse_error("attribute 'name' not allowed for a local simpleType", elem)
                xsd_type.name = None

        if 'final' in elem.attrib:
            try:
                xsd_type._final = get_xsd_derivation_attribute(elem, 'final')
            except ValueError as err:
                xsd_type.parse_error(err, elem)

        return xsd_type

    def create_any_content_group(self, parent: Union[XsdComplexType, XsdGroup],
                                 any_element: Optional[XsdAnyElement] = None) -> XsdGroup:
        """
        Creates a model group related to schema instance that accepts any content.

        :param parent: the parent component to set for the any content group.
        :param any_element: an optional any element to use for the content group. \
        When provided it's copied, linked to the group and the minOccurs/maxOccurs \
        are set to 0 and 'unbounded'.
        """
        group: XsdGroup = self.xsd_group_class(SEQUENCE_ELEMENT, self, parent)

        if isinstance(any_element, XsdAnyElement):
            particle = any_element.copy()
            particle.min_occurs = 0
            particle.max_occurs = None
            particle.parent = group
            group.append(particle)
        else:
            group.append(self.xsd_any_class(ANY_ELEMENT, self, group))

        return group

    def create_empty_content_group(self, parent: Union[XsdComplexType, XsdGroup],
                                   model: str = 'sequence', **attrib: Any) -> XsdGroup:
        if model == 'sequence':
            group_elem = etree_element(XSD_SEQUENCE, **attrib)
        elif model == 'choice':
            group_elem = etree_element(XSD_CHOICE, **attrib)
        elif model == 'all':
            group_elem = etree_element(XSD_ALL, **attrib)
        else:
            raise XMLSchemaValueError("'model' argument must be (sequence | choice | all)")

        group_elem.text = '\n    '
        return self.xsd_group_class(group_elem, self, parent)

    def create_any_attribute_group(self, parent: Union[XsdComplexType, XsdElement]) \
            -> XsdAttributeGroup:
        """
        Creates an attribute group related to schema instance that accepts any attribute.

        :param parent: the parent component to set for the any attribute group.
        """
        attribute_group = self.xsd_attribute_group_class(
            ATTRIBUTE_GROUP_ELEMENT, self, parent
        )
        attribute_group[None] = self.xsd_any_attribute_class(
            ANY_ATTRIBUTE_ELEMENT, self, attribute_group
        )
        return attribute_group

    def create_empty_attribute_group(self, parent: Union[XsdComplexType, XsdElement]) \
            -> XsdAttributeGroup:
        """
        Creates an empty attribute group related to schema instance.

        :param parent: the parent component to set for the any attribute group.
        """
        return self.xsd_attribute_group_class(ATTRIBUTE_GROUP_ELEMENT, self, parent)

    def create_any_type(self) -> XsdComplexType:
        """
        Creates an xs:anyType equivalent type related with the wildcards
        connected to global maps of the schema instance in order to do a
        correct namespace lookup during wildcards validation.
        """
        schema = self.meta_schema or self
        any_type = self.xsd_complex_type_class(
            elem=etree_element(XSD_COMPLEX_TYPE, name=XSD_ANY_TYPE),
            schema=schema, parent=None, mixed=True, block='', final=''
        )
        assert isinstance(any_type.content, XsdGroup)
        any_type.content.append(self.xsd_any_class(
            ANY_ELEMENT, schema, any_type.content
        ))
        any_type.attributes[None] = self.xsd_any_attribute_class(
            ANY_ATTRIBUTE_ELEMENT, schema, any_type.attributes
        )
        any_type.maps = any_type.content.maps = any_type.content[0].maps = \
            any_type.attributes[None].maps = self.maps
        return any_type

    def create_element(self, name: str, parent: Optional[XsdComponent] = None,
                       text: Optional[str] = None, **attrib: Any) -> XsdElement:
        """
        Creates an xs:element instance related to schema component.
        Used as dummy element for validation/decoding/encoding
        operations of wildcards and complex types.
        """
        elem = etree_element(XSD_ELEMENT, name=name, **attrib)
        if text is not None:
            elem.text = text
        return self.xsd_element_class(elem=elem, schema=self, parent=parent)

    def copy(self) -> SchemaType:
        """
        Makes a copy of the schema instance. The new instance has independent maps
        of shared XSD components.
        """
        schema: SchemaType = object.__new__(self.__class__)
        schema.__dict__.update(self.__dict__)
        schema.source = copy(self.source)
        schema.errors = self.errors[:]
        schema.warnings = self.warnings[:]
        schema.namespaces = dict(self.namespaces)
        schema.locations = NamespaceResourcesMap(self.locations)
        schema.imports = self.imports.copy()
        schema.includes = self.includes.copy()
        schema.maps = self.maps.copy(validator=schema)
        return schema

    __copy__ = copy

    @classmethod
    def check_schema(cls, schema: SchemaType,
                     namespaces: Optional[NamespacesType] = None) -> None:
        """
        Validates the given schema against the XSD meta-schema (:attr:`meta_schema`).

        :param schema: the schema instance that has to be validated.
        :param namespaces: is an optional mapping from namespace prefix to URI.

        :raises: :exc:`XMLSchemaValidationError` if the schema is invalid.
        """
        if cls.meta_schema is None:
            raise XMLSchemaRuntimeError("meta-schema unavailable for %r" % cls)
        elif not cls.meta_schema.maps.types:
            cls.meta_schema.maps.build()

        for error in cls.meta_schema.iter_errors(schema.source, namespaces=namespaces):
            raise error

    def check_validator(self, validation: str = 'strict') -> None:
        """Checks the status of a schema validator against a validation mode."""
        check_validation_mode(validation)

        if self.built:
            pass
        elif self.meta_schema is None:
            self.build()  # Meta-schema lazy build
        elif validation == 'skip' and self.validation == 'skip' and \
                any(isinstance(comp, tuple) or comp.validation_attempted == 'partial'
                    for comp in self.iter_globals()):
            pass
        else:
            raise XMLSchemaNotBuiltError(self, "schema %r is not built" % self)

    def build(self) -> None:
        """Builds the schema's XSD global maps."""
        self.maps.build()

    def clear(self) -> None:
        """Clears the schema's XSD global maps."""
        self.maps.clear()

    @property
    def built(self) -> bool:
        if any(not isinstance(g, XsdComponent) or not g.built for g in self.iter_globals()):
            return False
        for _ in self.iter_globals():
            return True
        if self.meta_schema is None:
            return False

        # No XSD globals: check with a lookup of schema child elements.
        prefix = '{%s}' % self.target_namespace if self.target_namespace else ''
        for child in self.source.root:
            if child.tag in {XSD_REDEFINE, XSD_OVERRIDE}:
                for e in filter(lambda x: x.tag in GLOBAL_TAGS, child):
                    name = e.get('name')
                    if name is not None:
                        try:
                            if not self.maps.lookup(e.tag, prefix + name if prefix else name).built:
                                return False
                        except KeyError:
                            return False
            elif child.tag in GLOBAL_TAGS:
                name = child.get('name')
                if name is not None:
                    try:
                        if not self.maps.lookup(child.tag, prefix + name if prefix else name).built:
                            return False
                    except KeyError:
                        return False
        return True

    @property
    def validation_attempted(self) -> str:
        if self.built:
            return 'full'
        elif any(isinstance(comp, tuple) or comp.validation_attempted == 'partial'
                 for comp in self.iter_globals()):
            return 'partial'
        else:
            return 'none'

    def iter_globals(self, schema: Optional[SchemaType] = None) \
            -> Iterator[Union[SchemaGlobalType, Tuple[Any, ...]]]:
        """
        Creates an iterator for XSD global definitions/declarations related to schema namespace.

        :param schema: Optional argument for filtering only globals related to a schema instance.
        """
        if schema is None:
            yield from self.notations.values()
            yield from self.types.values()
            yield from self.attributes.values()
            yield from self.attribute_groups.values()
            yield from self.groups.values()
            yield from self.elements.values()
        else:
            def schema_filter(x: Union[XsdComponent, Tuple[ElementType, SchemaType]]) -> bool:
                if isinstance(x, tuple):
                    return x[1] is schema
                return x.schema is schema

            yield from filter(schema_filter, self.notations.values())
            yield from filter(schema_filter, self.types.values())
            yield from filter(schema_filter, self.attributes.values())
            yield from filter(schema_filter, self.attribute_groups.values())
            yield from filter(schema_filter, self.groups.values())
            yield from filter(schema_filter, self.elements.values())

    def iter_components(self, xsd_classes: ComponentClassType = None) \
            -> Iterator[Union[XsdComponent, SchemaType]]:
        """
        Iterates yielding the schema and its components. For default
        includes all the relevant components of the schema, excluding
        only facets and empty attribute groups. The first returned
        component is the schema itself.

        :param xsd_classes: provide a class or a tuple of classes to \
        restrict the range of component types yielded.
        """
        if xsd_classes is None or isinstance(self, xsd_classes):
            yield self
        for xsd_global in self.iter_globals(self):
            if not isinstance(xsd_global, tuple):
                yield from xsd_global.iter_components(xsd_classes)

    def get_schema(self, namespace: str) -> SchemaType:
        """
        Returns the first schema loaded for a namespace. Raises a
        `KeyError` if the requested namespace is not loaded.
        """
        try:
            return cast(SchemaType, self.maps.namespaces[namespace][0])
        except KeyError:
            if not namespace:
                return self
            raise XMLSchemaKeyError('the namespace {!r} is not loaded'.format(namespace)) from None

    def get_converter(self, converter: Optional[ConverterType] = None,
                      **kwargs: Any) -> XMLSchemaConverter:
        """
        Returns a new converter instance.

        :param converter: can be a converter class or instance. If it's an instance \
        the new instance is copied from it and configured with the provided arguments.
        :param kwargs: optional arguments for initialize the converter instance.
        :return: a converter instance.
        """
        if converter is None:
            converter = self.converter

        if isinstance(converter, XMLSchemaConverter):
            return converter.copy(**kwargs)
        elif issubclass(converter, XMLSchemaConverter):
            # noinspection PyCallingNonCallable
            return converter(**kwargs)
        else:
            msg = "'converter' argument must be a %r subclass or instance: %r"
            raise XMLSchemaTypeError(msg % (XMLSchemaConverter, converter))

    def get_locations(self, namespace: str) -> List[str]:
        """Get a list of location hints for a namespace."""
        try:
            return list(self.locations[namespace])
        except KeyError:
            return []

    def get_element(self, tag: str, path: Optional[str] = None,
                    namespaces: Optional[NamespacesType] = None) -> Optional[XsdElement]:
        if not path:
            xsd_element = self.find(tag)
            return xsd_element if isinstance(xsd_element, XsdElement) else None
        elif path[-1] == '*':
            xsd_element = self.find(path[:-1] + tag, namespaces)
            if isinstance(xsd_element, XsdElement):
                return xsd_element

            obj = self.maps.elements.get(tag)
            return obj if isinstance(obj, XsdElement) else None
        else:
            xsd_element = self.find(path, namespaces)
            return xsd_element if isinstance(xsd_element, XsdElement) else None

    def create_bindings(self, *bases: type, **attrs: Any) -> None:
        """
        Creates data object bindings for XSD elements of the schema.

        :param bases: base classes to use for creating the binding classes.
        :param attrs: attribute and method definitions for the binding classes body.
        """
        for xsd_component in self.iter_components():
            if isinstance(xsd_component, XsdElement):
                xsd_component.get_binding(*bases, replace_existing=True, **attrs)

    def _parse_inclusions(self) -> None:
        """Processes schema document inclusions and redefinitions/overrides."""
        for child in self.source.root:
            if child.tag == XSD_INCLUDE:
                try:
                    location = child.attrib['schemaLocation'].strip()
                    logger.info("Include schema from %r", location)
                    self.include_schema(location, self.base_url)
                except KeyError:
                    # Attribute missing error already found by validation against meta-schema
                    pass
                except (OSError, IOError) as err:
                    # It is not an error if the location fail to resolve:
                    #   https://www.w3.org/TR/2012/REC-xmlschema11-1-20120405/#compound-schema
                    #   https://www.w3.org/TR/2012/REC-xmlschema11-1-20120405/#src-include
                    self.warnings.append("Include schema failed: %s." % str(err))
                    warnings.warn(self.warnings[-1], XMLSchemaIncludeWarning, stacklevel=3)
                except (XMLSchemaParseError, XMLSchemaTypeError, ParseError) as err:
                    msg = 'cannot include schema %r: %s' % (child.attrib['schemaLocation'], err)
                    if isinstance(err, (XMLSchemaParseError, ParseError)):
                        self.parse_error(msg)
                    else:
                        raise type(err)(msg)

            elif child.tag == XSD_REDEFINE:
                try:
                    location = child.attrib['schemaLocation'].strip()
                    logger.info("Redefine schema %r", location)
                    schema = self.include_schema(location, self.base_url)
                except KeyError:
                    # Attribute missing error already found by validation against meta-schema
                    pass
                except (OSError, IOError) as err:
                    # If the redefine doesn't contain components (annotation excluded)
                    # the statement is equivalent to an include, so no error is generated.
                    # Otherwise fails.
                    self.warnings.append("Redefine schema failed: %s." % str(err))
                    warnings.warn(self.warnings[-1], XMLSchemaIncludeWarning, stacklevel=3)
                    if any(e.tag != XSD_ANNOTATION and not callable(e.tag) for e in child):
                        self.parse_error(err, child)
                except (XMLSchemaParseError, XMLSchemaTypeError, ParseError) as err:
                    msg = 'cannot redefine schema %r: %s' % (child.attrib['schemaLocation'], err)
                    if isinstance(err, (XMLSchemaParseError, ParseError)):
                        self.parse_error(msg, child)
                    else:
                        raise type(err)(msg)
                else:
                    schema.redefine = self

            elif child.tag == XSD_OVERRIDE and self.XSD_VERSION != '1.0':
                try:
                    location = child.attrib['schemaLocation'].strip()
                    logger.info("Override schema %r", location)
                    schema = self.include_schema(location, self.base_url)
                except KeyError:
                    # Attribute missing error already found by validation against meta-schema
                    pass
                except (OSError, IOError) as err:
                    # If the override doesn't contain components (annotation excluded)
                    # the statement is equivalent to an include, so no error is generated.
                    # Otherwise fails.
                    self.warnings.append("Override schema failed: %s." % str(err))
                    warnings.warn(self.warnings[-1], XMLSchemaIncludeWarning, stacklevel=3)
                    if any(e.tag != XSD_ANNOTATION and not callable(e.tag) for e in child):
                        self.parse_error(str(err), child)
                else:
                    schema.override = self

    def include_schema(self, location: str, base_url: Optional[str] = None,
                       build: bool = False) -> SchemaType:
        """
        Includes a schema for the same namespace, from a specific URL.

        :param location: is the URL of the schema.
        :param base_url: is an optional base URL for fetching the schema resource.
        :param build: defines when to build the imported schema, the default is to not build.
        :return: the included :class:`XMLSchema` instance.
        """
        schema: SchemaType
        schema_url = fetch_resource(location, base_url)
        for schema in self.maps.namespaces[self.target_namespace]:
            if schema_url == schema.url:
                logger.info("Resource %r is already loaded", location)
                break
        else:
            schema = type(self)(
                source=schema_url,
                namespace=self.target_namespace,
                validation=self.validation,
                global_maps=self.maps,
                converter=self.converter,
                locations=self._locations,
                base_url=self.base_url,
                allow=self.allow,
                defuse=self.defuse,
                timeout=self.timeout,
                build=build,
            )

        if schema is self:
            return self
        elif location not in self.includes:
            self.includes[location] = schema
        elif self.includes[location] is not schema:
            self.includes[schema_url] = schema
        return schema

    def _parse_imports(self) -> None:
        """
        Parse namespace import elements. Imports are done on namespace basis, not on
        single resource. A warning is generated for a failure of a namespace import.
        """
        namespace_imports = NamespaceResourcesMap(map(
            lambda x: (x.get('namespace'), x.get('schemaLocation')),
            filter(lambda x: x.tag == XSD_IMPORT, self.source.root)
        ))

        for namespace, locations in namespace_imports.items():

            # Checks the namespace against the targetNamespace of the schema
            if namespace is None:
                namespace = ''
                if namespace == self.target_namespace:
                    self.parse_error("if the 'namespace' attribute is not present on "
                                     "the import statement then the importing schema "
                                     "must have a 'targetNamespace'")
                    continue
            elif namespace == self.target_namespace:
                self.parse_error("the attribute 'namespace' must be different from "
                                 "schema's 'targetNamespace'")
                continue

            # Skip import of already imported namespaces
            if self.imports.get(namespace) is not None:
                continue
            elif namespace in self.maps.namespaces:
                self.imports[namespace] = self.maps.namespaces[namespace][0]
                continue

            locations = [url for url in locations if url]
            if not namespace:
                pass
            elif not locations:
                locations = self.get_locations(namespace)
            elif all(is_remote_url(url) for url in locations):
                # If all import schema locations are remote URLs and there are local hints
                # that match a local file path, try the local hints before schema locations.
                # This is not the standard processing for XSD imports, but resolve the problem
                # of local processing of schemas tested to work from a http server, providing
                # explicit local hints.
                local_hints = [url for url in self.get_locations(namespace)
                               if url and url_path_is_file(url)]
                if local_hints:
                    locations = local_hints + locations

            if namespace in self.fallback_locations:
                locations.append(self.fallback_locations[namespace])

            self._import_namespace(namespace, locations)

    def _import_namespace(self, namespace: str, locations: List[str]) -> None:
        import_error = None
        for url in locations:
            try:
                logger.debug("Import namespace %r from %r", namespace, url)
                self.import_schema(namespace, url, self.base_url)
            except (OSError, IOError) as err:
                # It's not an error if the location access fails (ref. section 4.2.6.2):
                #   https://www.w3.org/TR/2012/REC-xmlschema11-1-20120405/#composition-schemaImport
                logger.debug('%s', err)
                if import_error is None:
                    import_error = err
            except (XMLSchemaParseError, XMLSchemaTypeError, ParseError) as err:
                if namespace:
                    msg = "cannot import namespace %r: %s." % (namespace, err)
                else:
                    msg = "cannot import chameleon schema: %s." % err
                if isinstance(err, (XMLSchemaParseError, ParseError)):
                    self.parse_error(msg)
                else:
                    raise type(err)(msg)
            except XMLSchemaValueError as err:
                self.parse_error(err)
            else:
                logger.info("Namespace %r imported from %r", namespace, url)
                break
        else:
            if import_error is not None:
                msg = "Import of namespace {!r} from {!r} failed: {}."
                self.warnings.append(msg.format(namespace, locations, str(import_error)))
                warnings.warn(self.warnings[-1], XMLSchemaImportWarning, stacklevel=4)
            self.imports[namespace] = None

    def import_schema(self, namespace: str, location: str, base_url: Optional[str] = None,
                      force: bool = False, build: bool = False) -> Optional[SchemaType]:
        """
        Imports a schema for an external namespace, from a specific URL.

        :param namespace: is the URI of the external namespace.
        :param location: is the URL of the schema.
        :param base_url: is an optional base URL for fetching the schema resource.
        :param force: if set to `True` imports the schema also if the namespace is already imported.
        :param build: defines when to build the imported schema, the default is to not build.
        :return: the imported :class:`XMLSchema` instance.
        """
        if location == self.url:
            return self

        if not force:
            if self.imports.get(namespace) is not None:
                return self.imports[namespace]
            elif namespace in self.maps.namespaces:
                self.imports[namespace] = self.maps.namespaces[namespace][0]
                return self.imports[namespace]

        schema: SchemaType
        schema_url = fetch_resource(location, base_url)
        imported_ns = self.imports.get(namespace)
        if imported_ns is not None and imported_ns.url == schema_url:
            return imported_ns
        elif namespace in self.maps.namespaces:
            for schema in self.maps.namespaces[namespace]:
                if schema_url == schema.url:
                    self.imports[namespace] = schema
                    return schema

        schema = type(self)(
            source=schema_url,
            validation=self.validation,
            global_maps=self.maps,
            converter=self.converter,
            locations=self._locations,
            base_url=self.base_url,
            allow=self.allow,
            defuse=self.defuse,
            timeout=self.timeout,
            build=build,
        )
        if schema.target_namespace != namespace:
            raise XMLSchemaValueError(
                'imported schema %r has an unmatched namespace %r' % (location, namespace)
            )
        self.imports[namespace] = schema
        return schema

    def add_schema(self, source: SchemaSourceType,
                   namespace: Optional[str] = None, build: bool = False) -> SchemaType:
        """
        Add another schema source to the maps of the instance.

        :param source: an URI that reference to a resource or a file path or a file-like \
        object or a string containing the schema or an Element or an ElementTree document.
        :param namespace: is an optional argument that contains the URI of the namespace \
        that has to used in case the schema has no namespace (chameleon schema). For other \
        cases, when specified, it must be equal to the *targetNamespace* of the schema.
        :param build: defines when to build the imported schema, the default is to not build.
        :return: the added :class:`XMLSchema` instance.
        """
        return type(self)(
            source=source,
            namespace=namespace,
            validation=self.validation,
            global_maps=self.maps,
            converter=self.converter,
            locations=self._locations,
            base_url=self.base_url,
            allow=self.allow,
            defuse=self.defuse,
            timeout=self.timeout,
            build=build,
        )

    def export(self, target: str, save_remote: bool = False) -> None:
        """
        Exports a schema instance. The schema instance is exported to a
        directory with also the hierarchy of imported/included schemas.

        :param target: a path to a local empty directory.
        :param save_remote: if `True` is provided saves also remote schemas.
        """
        import pathlib
        from urllib.parse import urlsplit

        target_path = pathlib.Path(target)
        if target_path.is_dir():
            if list(target_path.iterdir()):
                raise XMLSchemaValueError("target directory {!r} is not empty".format(target))
        elif target_path.exists():
            msg = "target {} is not a directory"
            raise XMLSchemaValueError(msg.format(target_path.parent))
        elif not target_path.parent.exists():
            msg = "target parent directory {} does not exist"
            raise XMLSchemaValueError(msg.format(target_path.parent))
        elif not target_path.parent.is_dir():
            msg = "target parent {} is not a directory"
            raise XMLSchemaValueError(msg.format(target_path.parent))

        url = self.url or 'schema.xsd'
        basename = pathlib.Path(urlsplit(url).path).name
        exports: Any = {self: [target_path.joinpath(basename), self.get_text()]}
        path: Any

        while True:
            current_length = len(exports)

            for schema in list(exports):
                dir_path = exports[schema][0].parent
                imports_items = [(x.url, x) for x in schema.imports.values() if x is not None]

                for location, ref_schema in chain(schema.includes.items(), imports_items):
                    if ref_schema in exports:
                        continue

                    if is_remote_url(location):
                        if not save_remote:
                            continue
                        url_parts = urlsplit(location)
                        netloc, path = url_parts.netloc, url_parts.path
                        path = pathlib.Path().joinpath(netloc).joinpath(path.lstrip('/'))
                    else:
                        if location.startswith('file:/'):
                            location = urlsplit(location).path

                        path = pathlib.Path(location)
                        if path.is_absolute():
                            location = '/'.join(path.parts[-2:])
                            try:
                                schema_path = pathlib.Path(schema.filepath)
                            except TypeError:
                                pass
                            else:
                                try:
                                    path = path.relative_to(schema_path.parent)
                                except ValueError:
                                    parts = path.parts
                                    if parts[:-2] == schema_path.parts[:-2]:
                                        path = pathlib.Path(location)
                                else:
                                    path = dir_path.joinpath(path)
                                    exports[ref_schema] = [path, ref_schema.get_text()]
                                    continue

                        elif not str(path).startswith('..'):
                            path = dir_path.joinpath(path)
                            exports[ref_schema] = [path, ref_schema.get_text()]
                            continue

                        if DRIVE_PATTERN.match(path.parts[0]):
                            path = pathlib.Path().joinpath(path.parts[1:])

                        for strip_path in ('/', '\\', '..'):
                            while True:
                                try:
                                    path = path.relative_to(strip_path)
                                except ValueError:
                                    break

                    path = target_path.joinpath(path)
                    repl = 'schemaLocation="{}"'.format(path.as_posix())
                    schema_text = exports[schema][1]
                    pattern = r'\bschemaLocation\s*=\s*[\'\"].*%s.*[\'"]' % re.escape(location)
                    exports[schema][1] = re.sub(pattern, repl, schema_text)
                    exports[ref_schema] = [path, ref_schema.get_text()]

            if current_length == len(exports):
                break

        for schema, (path, text) in exports.items():
            if not path.parent.exists():
                path.parent.mkdir(parents=True)

            with path.open(mode='w') as fp:
                fp.write(text)

    def version_check(self, elem: ElementType) -> bool:
        """
        Checks if the element is compatible with the version of the validator and XSD
        types/facets availability. Invalid vc attributes are not detected in XSD 1.0.

        :param elem: an Element of the schema.
        :return: `True` if the schema element is compatible with the validator, \
        `False` otherwise.
        """
        if VC_MIN_VERSION in elem.attrib:
            vc_min_version = elem.attrib[VC_MIN_VERSION]
            if not XSD_VERSION_PATTERN.match(vc_min_version):
                if self.XSD_VERSION > '1.0':
                    self.parse_error("invalid attribute vc:minVersion value", elem)
            elif vc_min_version > self.XSD_VERSION:
                return False

        if VC_MAX_VERSION in elem.attrib:
            vc_max_version = elem.attrib[VC_MAX_VERSION]
            if not XSD_VERSION_PATTERN.match(vc_max_version):
                if self.XSD_VERSION > '1.0':
                    self.parse_error("invalid attribute vc:maxVersion value", elem)
            elif vc_max_version <= self.XSD_VERSION:
                return False

        if VC_TYPE_AVAILABLE in elem.attrib:
            for qname in elem.attrib[VC_TYPE_AVAILABLE].split():
                try:
                    if self.resolve_qname(qname) not in self.maps.types:
                        return False
                except XMLSchemaNamespaceError:
                    return False
                except (KeyError, ValueError) as err:
                    self.parse_error(str(err), elem)

        if VC_TYPE_UNAVAILABLE in elem.attrib:
            for qname in elem.attrib[VC_TYPE_UNAVAILABLE].split():
                try:
                    if self.resolve_qname(qname) not in self.maps.types:
                        break
                except XMLSchemaNamespaceError:
                    break
                except (KeyError, ValueError) as err:
                    self.parse_error(err, elem)
            else:
                return False

        if VC_FACET_AVAILABLE in elem.attrib:
            for qname in elem.attrib[VC_FACET_AVAILABLE].split():
                try:
                    facet_name = self.resolve_qname(qname)
                except XMLSchemaNamespaceError:
                    pass
                except (KeyError, ValueError) as err:
                    self.parse_error(str(err), elem)
                else:
                    if self.XSD_VERSION == '1.0':
                        if facet_name not in XSD_10_FACETS:
                            return False
                    elif facet_name not in XSD_11_FACETS:
                        return False

        if VC_FACET_UNAVAILABLE in elem.attrib:
            for qname in elem.attrib[VC_FACET_UNAVAILABLE].split():
                try:
                    facet_name = self.resolve_qname(qname)
                except XMLSchemaNamespaceError:
                    break
                except (KeyError, ValueError) as err:
                    self.parse_error(err, elem)
                else:
                    if self.XSD_VERSION == '1.0':
                        if facet_name not in XSD_10_FACETS:
                            break
                    elif facet_name not in XSD_11_FACETS:
                        break
            else:
                return False

        return True

    def resolve_qname(self, qname: str, namespace_imported: bool = True) -> str:
        """
        QName resolution for a schema instance.

        :param qname: a string in xs:QName format.
        :param namespace_imported: if this argument is `True` raises an \
        `XMLSchemaNamespaceError` if the namespace of the QName is not the \
        *targetNamespace* and the namespace is not imported by the schema.
        :returns: an expanded QName in the format "{*namespace-URI*}*local-name*".
        :raises: `XMLSchemaValueError` for an invalid xs:QName is found, \
        `XMLSchemaKeyError` if the namespace prefix is not declared in the \
        schema instance.
        """
        qname = qname.strip()
        if not qname or ' ' in qname or '\t' in qname or '\n' in qname:
            raise XMLSchemaValueError("{!r} is not a valid value for xs:QName".format(qname))

        if qname[0] == '{':
            try:
                namespace, local_name = qname[1:].split('}')
            except ValueError:
                raise XMLSchemaValueError("{!r} is not a valid value for xs:QName".format(qname))
        elif ':' in qname:
            try:
                prefix, local_name = qname.split(':')
            except ValueError:
                raise XMLSchemaValueError("{!r} is not a valid value for xs:QName".format(qname))
            else:
                try:
                    namespace = self.namespaces[prefix]
                except KeyError:
                    raise XMLSchemaKeyError("prefix %r not found in namespace map" % prefix)
        else:
            namespace, local_name = self.namespaces.get('', ''), qname

        if not namespace:
            if namespace_imported and self.target_namespace and '' not in self.imports:
                raise XMLSchemaNamespaceError(
                    "the QName {!r} is mapped to no namespace, but this requires "
                    "that there is an xs:import statement in the schema without "
                    "the 'namespace' attribute.".format(qname)
                )
            return local_name
        elif namespace_imported and self.meta_schema is not None and \
                namespace != self.target_namespace and \
                namespace not in {XSD_NAMESPACE, XSI_NAMESPACE} and \
                namespace not in self.imports:
            raise XMLSchemaNamespaceError(
                "the QName {!r} is mapped to the namespace {!r}, but this namespace has "
                "not an xs:import statement in the schema.".format(qname, namespace)
            )
        return '{%s}%s' % (namespace, local_name)

    def validate(self, source: Union[XMLSourceType, XMLResource],
                 path: Optional[str] = None,
                 schema_path: Optional[str] = None,
                 use_defaults: bool = True,
                 namespaces: Optional[NamespacesType] = None,
                 max_depth: Optional[int] = None,
                 extra_validator: Optional[ExtraValidatorType] = None) -> None:
        """
        Validates an XML data against the XSD schema/component instance.

        :param source: the source of XML data. Can be an :class:`XMLResource` instance, a \
        path to a file or an URI of a resource or an opened file-like object or an Element \
        instance or an ElementTree instance or a string containing the XML data.
        :param path: is an optional XPath expression that matches the elements of the XML \
        data that have to be decoded. If not provided the XML root element is selected.
        :param schema_path: an alternative XPath expression to select the XSD element \
        to use for decoding. Useful if the root of the XML data doesn't match an XSD \
        global element of the schema.
        :param use_defaults: Use schema's default values for filling missing data.
        :param namespaces: is an optional mapping from namespace prefix to URI.
        :param max_depth: maximum level of validation, for default there is no limit. \
        With lazy resources is set to `source.lazy_depth` for managing lazy validation.
        :param extra_validator: an optional function for performing non-standard \
        validations on XML data. The provided function is called for each traversed \
        element, with the XML element as 1st argument and the corresponding XSD \
        element as 2nd argument. It can be also a generator function and has to \
        raise/yield :exc:`XMLSchemaValidationError` exceptions.
        :raises: :exc:`XMLSchemaValidationError` if the XML data instance is invalid.
        """
        for error in self.iter_errors(source, path, schema_path, use_defaults,
                                      namespaces, max_depth, extra_validator):
            raise error

    def is_valid(self, source: Union[XMLSourceType, XMLResource],
                 path: Optional[str] = None,
                 schema_path: Optional[str] = None,
                 use_defaults: bool = True,
                 namespaces: Optional[NamespacesType] = None,
                 max_depth: Optional[int] = None,
                 extra_validator: Optional[ExtraValidatorType] = None) -> bool:
        """
        Like :meth:`validate` except that does not raise an exception but returns
        ``True`` if the XML data instance is valid, ``False`` if it is invalid.
        """
        error = next(self.iter_errors(source, path, schema_path, use_defaults,
                                      namespaces, max_depth, extra_validator), None)
        return error is None

    def iter_errors(self, source: Union[XMLSourceType, XMLResource],
                    path: Optional[str] = None,
                    schema_path: Optional[str] = None,
                    use_defaults: bool = True,
                    namespaces: Optional[NamespacesType] = None,
                    max_depth: Optional[int] = None,
                    extra_validator: Optional[ExtraValidatorType] = None) \
            -> Iterator[XMLSchemaValidationError]:
        """
        Creates an iterator for the errors generated by the validation of an XML data against
        the XSD schema/component instance. Accepts the same arguments of :meth:`validate`.
        """
        self.check_validator(validation='lax')
        if isinstance(source, XMLResource):
            resource: XMLResource = source
        else:
            resource = XMLResource(source, defuse=self.defuse, timeout=self.timeout)

        if not schema_path:
            schema_path = resource.get_absolute_path(path)

        namespaces = resource.get_namespaces(namespaces, root_only=True)
        namespace = resource.namespace or namespaces.get('', '')

        try:
            schema = self.get_schema(namespace)
        except KeyError:
            schema = self

        identities: Dict[XsdIdentity, IdentityCounter] = {}
        locations: List[Any] = []
        ancestors: List[ElementType] = []
        prev_ancestors: List[ElementType] = []
        kwargs: Dict[Any, Any] = {
            'level': resource.lazy_depth or bool(path),
            'source': resource,
            'namespaces': namespaces,
            'converter': None,
            'use_defaults': use_defaults,
            'id_map': Counter[str](),
            'identities': identities,
            'inherited': {},
            'locations': locations,  # TODO: lazy schemas load
        }
        if max_depth is not None:
            kwargs['max_depth'] = max_depth
        if extra_validator is not None:
            kwargs['extra_validator'] = extra_validator

        if path:
            selector = resource.iterfind(path, namespaces, nsmap=namespaces, ancestors=ancestors)
        else:
            selector = resource.iter_depth(mode=3, nsmap=namespaces, ancestors=ancestors)

        for elem in selector:
            if elem is resource.root:
                xsd_element = schema.get_element(elem.tag, namespaces=namespaces)
                if resource.lazy_depth:
                    kwargs['level'] = 0
                    kwargs['identities'] = {}
                    kwargs['max_depth'] = resource.lazy_depth
            else:
                if prev_ancestors != ancestors:
                    k = 0
                    for k in range(min(len(ancestors), len(prev_ancestors))):
                        if ancestors[k] is not prev_ancestors[k]:
                            break

                    path_ = '/'.join(e.tag for e in ancestors) + '/ancestor-or-self::node()'
                    xsd_ancestors = cast(List[XsdElement], schema.findall(path_, namespaces)[1:])

                    for e in xsd_ancestors[k:]:
                        e.stop_identities(identities)

                    for e in xsd_ancestors[k:]:
                        e.start_identities(identities)

                    prev_ancestors = ancestors[:]

                xsd_element = schema.get_element(elem.tag, schema_path, namespaces)

            if xsd_element is None:
                if XSI_TYPE in elem.attrib:
                    xsd_element = self.create_element(name=elem.tag)
                elif elem is not resource.root and ancestors:
                    continue
                else:
                    reason = "{!r} is not an element of the schema".format(elem)
                    yield schema.validation_error('lax', reason, elem, resource, namespaces)
                    return

            for result in xsd_element.iter_decode(elem, **kwargs):
                if isinstance(result, XMLSchemaValidationError):
                    yield result
                else:
                    del result

        if kwargs['identities'] is not identities:
            identity: XsdIdentity
            counter: IdentityCounter
            for identity, counter in kwargs['identities'].items():
                identities[identity].counter.update(counter.counter)
            kwargs['identities'] = identities

        yield from self._validate_references(validation='lax', **kwargs)

    def _validate_references(self, source: XMLResource,
                             validation: str = 'lax',
                             id_map: Optional[Counter[str]] = None,
                             identities: Optional[IdentityMapType] = None,
                             **kwargs: Any) -> Iterator[XMLSchemaValidationError]:
        # Check unresolved IDREF values
        if id_map is not None:
            for k, v in id_map.items():
                if v == 0:
                    msg = "IDREF %r not found in XML document" % k
                    yield self.validation_error(validation, msg, source.root)

        # Check still enabled key references (lazy validation cases)
        if identities is not None:
            for constraint, counter in identities.items():
                if counter.enabled and isinstance(constraint, XsdKeyref):
                    for error in cast(KeyrefCounter, counter).iter_errors(identities):
                        yield self.validation_error(validation, error, source.root, **kwargs)

    def raw_decoder(self, source: XMLResource, path: Optional[str] = None,
                    schema_path: Optional[str] = None, validation: str = 'lax',
                    namespaces: Optional[NamespacesType] = None, **kwargs: Any) \
            -> Iterator[Union[Any, XMLSchemaValidationError]]:
        """Returns a generator for decoding a resource."""
        if path:
            selector = source.iterfind(path, namespaces, nsmap=namespaces)
        else:
            selector = source.iter_depth(nsmap=namespaces)

        for elem in selector:
            xsd_element = self.get_element(elem.tag, schema_path, namespaces)
            if xsd_element is None:
                if XSI_TYPE in elem.attrib:
                    xsd_element = self.create_element(name=elem.tag)
                else:
                    reason = "{!r} is not an element of the schema".format(elem)
                    yield self.validation_error(validation, reason, elem, source, namespaces)
                    continue

            yield from xsd_element.iter_decode(elem, validation, **kwargs)

        if 'max_depth' not in kwargs:
            yield from self._validate_references(source, validation=validation, **kwargs)

    def iter_decode(self, source: Union[XMLSourceType, XMLResource],
                    path: Optional[str] = None,
                    schema_path: Optional[str] = None,
                    validation: str = 'lax',
                    process_namespaces: bool = True,
                    namespaces: Optional[NamespacesType] = None,
                    use_defaults: bool = True,
                    decimal_type: Optional[Type[Any]] = None,
                    datetime_types: bool = False,
                    binary_types: bool = False,
                    converter: Optional[ConverterType] = None,
                    filler: Optional[Callable[[Union[XsdElement, XsdAttribute]], Any]] = None,
                    fill_missing: bool = False,
                    keep_unknown: bool = False,
                    process_skipped: bool = False,
                    max_depth: Optional[int] = None,
                    depth_filler: Optional[Callable[[XsdElement], Any]] = None,
                    value_hook: Optional[Callable[[AtomicValueType, BaseXsdType], Any]] = None,
                    **kwargs: Any) -> Iterator[Union[Any, XMLSchemaValidationError]]:
        """
        Creates an iterator for decoding an XML source to a data structure.

        :param source: the source of XML data. Can be an :class:`XMLResource` instance, a \
        path to a file or an URI of a resource or an opened file-like object or an Element \
        instance or an ElementTree instance or a string containing the XML data.
        :param path: is an optional XPath expression that matches the elements of the XML \
        data that have to be decoded. If not provided the XML root element is selected.
        :param schema_path: an alternative XPath expression to select the XSD element \
        to use for decoding. Useful if the root of the XML data doesn't match an XSD \
        global element of the schema.
        :param validation: defines the XSD validation mode to use for decode, can be \
        'strict', 'lax' or 'skip'.
        :param process_namespaces: whether to use namespace information in the \
        decoding process, using the map provided with the argument *namespaces* \
        and the map extracted from the XML document.
        :param namespaces: is an optional mapping from namespace prefix to URI.
        :param use_defaults: whether to use default values for filling missing data.
        :param decimal_type: conversion type for `Decimal` objects (generated by \
        `xs:decimal` built-in and derived types), useful if you want to generate a \
        JSON-compatible data structure.
        :param datetime_types: if set to `True` the datetime and duration XSD types \
        are kept decoded, otherwise their origin XML string is returned.
        :param binary_types: if set to `True` xs:hexBinary and xs:base64Binary types \
        are kept decoded, otherwise their origin XML string is returned.
        :param converter: an :class:`XMLSchemaConverter` subclass or instance to use \
        for decoding.
        :param filler: an optional callback function to fill undecodable data with a \
        typed value. The callback function must accept one positional argument, that \
        can be an XSD Element or an attribute declaration. If not provided undecodable \
        data is replaced by `None`.
        :param fill_missing: if set to `True` the decoder fills also missing attributes. \
        The filling value is `None` or a typed value if the *filler* callback is provided.
        :param keep_unknown: if set to `True` unknown tags are kept and are decoded with \
        *xs:anyType*. For default unknown tags not decoded by a wildcard are discarded.
        :param process_skipped: process XML data that match a wildcard with \
        `processContents='skip'`.
        :param max_depth: maximum level of decoding, for default there is no limit. \
        With lazy resources is set to `source.lazy_depth` for managing lazy decoding.
        :param depth_filler: an optional callback function to replace data over the \
        *max_depth* level. The callback function must accept one positional argument, that \
        can be an XSD Element. If not provided deeper data are replaced with `None` values.
        :param value_hook: an optional function that will be called with any decoded \
        atomic value and the XSD type used for decoding. The return value will be used \
        instead of the original value.
        :param kwargs: keyword arguments with other options for converter and decoder.
        :return: yields a decoded data object, eventually preceded by a sequence of \
        validation or decoding errors.
        """
        self.check_validator(validation)
        if isinstance(source, XMLResource):
            resource: XMLResource = source
        else:
            resource = XMLResource(source, defuse=self.defuse, timeout=self.timeout)

        if not schema_path and path:
            schema_path = resource.get_absolute_path(path)

        if process_namespaces:
            namespaces = resource.get_namespaces(namespaces, root_only=True)
            namespace = resource.namespace or namespaces.get('', '')
        else:
            namespace = resource.namespace

        schema = self.get_schema(namespace)
        converter = self.get_converter(converter, namespaces=namespaces, **kwargs)
        kwargs.update(
            converter=converter,
            namespaces=namespaces,
            source=resource,
            use_defaults=use_defaults,
            id_map=Counter[str](),
            identities={},
            inherited={},
        )

        if decimal_type is not None:
            kwargs['decimal_type'] = decimal_type
        if datetime_types:
            kwargs['datetime_types'] = datetime_types
        if binary_types:
            kwargs['binary_types'] = binary_types
        if filler is not None:
            kwargs['filler'] = filler
        if fill_missing:
            kwargs['fill_missing'] = fill_missing
        if keep_unknown:
            kwargs['keep_unknown'] = keep_unknown
        if process_skipped:
            kwargs['process_skipped'] = process_skipped
        if max_depth is not None:
            kwargs['max_depth'] = max_depth
        if depth_filler is not None:
            kwargs['depth_filler'] = depth_filler
        if value_hook is not None:
            kwargs['value_hook'] = value_hook

        if path:
            selector = resource.iterfind(path, namespaces, nsmap=namespaces)
        elif not resource.is_lazy():
            selector = resource.iter_depth(nsmap=namespaces)
        else:
            decoder = self.raw_decoder(
                schema_path=resource.get_absolute_path(),
                validation=validation,
                **kwargs
            )
            kwargs['depth_filler'] = lambda x: decoder
            kwargs['max_depth'] = resource.lazy_depth
            selector = resource.iter_depth(mode=2, nsmap=namespaces)

        for elem in selector:
            xsd_element = schema.get_element(elem.tag, schema_path, namespaces)
            if xsd_element is None:
                if XSI_TYPE in elem.attrib:
                    xsd_element = self.create_element(name=elem.tag)
                else:
                    reason = "{!r} is not an element of the schema".format(elem)
                    yield schema.validation_error(validation, reason, elem, resource, namespaces)
                    return

            yield from xsd_element.iter_decode(elem, validation, **kwargs)

        if 'max_depth' not in kwargs:
            yield from self._validate_references(validation=validation, **kwargs)

    def decode(self, source: Union[XMLSourceType, XMLResource],
               path: Optional[str] = None,
               schema_path: Optional[str] = None,
               validation: str = 'strict',
               *args: Any, **kwargs: Any) -> DecodeType[Any]:
        """
        Decodes XML data. Takes the same arguments of the method :func:`XMLSchema.iter_decode`.
        """
        data, errors = [], []
        for result in self.iter_decode(source, path, schema_path, validation, *args, **kwargs):
            if not isinstance(result, XMLSchemaValidationError):
                data.append(result)
            elif validation == 'lax':
                errors.append(result)
            elif validation == 'strict':
                raise result

        if not data:
            return (None, errors) if validation == 'lax' else None
        elif len(data) == 1:
            return (data[0], errors) if validation == 'lax' else data[0]
        else:
            return (data, errors) if validation == 'lax' else data

    to_dict = decode

    def to_objects(self, source: Union[XMLSourceType, XMLResource], with_bindings: bool = False,
                   **kwargs: Any) -> DecodeType['dataobjects.DataElement']:
        """
        Decodes XML data to Python data objects.

        :param source: the XML data. Can be a string for an attribute or for a simple \
        type components or a dictionary for an attribute group or an ElementTree's \
        Element for other components.
        :param with_bindings: if `True` is provided the decoding is done using \
        :class:`DataBindingConverter` that used XML data binding classes. For \
        default the objects are instances of :class:`DataElement` and uses the \
        :class:`DataElementConverter`.
        :param kwargs: other optional keyword arguments for the method \
        :func:`iter_decode`, except the argument *converter*.
        """
        if with_bindings:
            return self.decode(source, converter=dataobjects.DataBindingConverter, **kwargs)
        return self.decode(source, converter=dataobjects.DataElementConverter, **kwargs)

    def iter_encode(self, obj: Any, path: Optional[str] = None, validation: str = 'lax',
                    namespaces: Optional[NamespacesType] = None, use_defaults: bool = True,
                    converter: Optional[ConverterType] = None, unordered: bool = False,
                    **kwargs: Any) -> Iterator[Union[ElementType, XMLSchemaValidationError]]:
        """
        Creates an iterator for encoding a data structure to an ElementTree's Element.

        :param obj: the data that has to be encoded to XML data.
        :param path: is an optional XPath expression for selecting the element of \
        the schema that matches the data that has to be encoded. For default the first \
        global element of the schema is used.
        :param validation: the XSD validation mode. Can be 'strict', 'lax' or 'skip'.
        :param namespaces: is an optional mapping from namespace prefix to URI.
        :param use_defaults: whether to use default values for filling missing data.
        :param converter: an :class:`XMLSchemaConverter` subclass or instance to use for \
        the encoding.
        :param unordered: a flag for explicitly activating unordered encoding mode for \
        content model data. This mode uses content models for a reordered-by-model \
        iteration of the child elements.
        :param kwargs: keyword arguments with other options for encoding and for \
        building the converter instance.
        :return: yields an Element instance/s or validation/encoding errors.
        """
        self.check_validator(validation)
        if not self.elements:
            raise XMLSchemaValueError("encoding needs at least one XSD element declaration!")

        if namespaces is None:
            namespaces = {}
        else:
            namespaces = {k: v for k, v in namespaces.items()}

        converter = self.get_converter(converter, namespaces=namespaces, **kwargs)

        xsd_element = None
        if path is not None:
            match = re.search(r'[{\w]', path)
            if match:
                namespace = get_namespace(path[match.start():], namespaces)
                schema = self.get_schema(namespace)
                xsd_element = schema.find(path, namespaces)

        elif len(self.elements) == 1:
            xsd_element = list(self.elements.values())[0]
        else:
            root_elements = self.root_elements
            if len(root_elements) == 1:
                xsd_element = root_elements[0]
            elif isinstance(obj, (converter.dict, dict)) and len(obj) == 1:
                for key in obj:
                    match = re.search(r'[{\w]', key)
                    if match:
                        namespace = get_namespace(key[match.start():], namespaces)
                        schema = self.get_schema(namespace)
                        xsd_element = schema.find(key, namespaces)

        if not isinstance(xsd_element, XsdElement):
            if path is not None:
                reason = "the path %r doesn't match any element of the schema!" % path
            else:
                reason = "unable to select an element for decoding data, " \
                         "provide a valid 'path' argument."
            raise XMLSchemaEncodeError(self, obj, self.elements, reason, namespaces=namespaces)
        else:
            yield from xsd_element.iter_encode(obj, validation, use_defaults=use_defaults,
                                               converter=converter, unordered=unordered, **kwargs)

    def encode(self, obj: Any, path: Optional[str] = None, validation: str = 'strict',
               *args: Any, **kwargs: Any) -> EncodeType[Any]:
        """
        Encodes to XML data. Takes the same arguments of the method :func:`XMLSchema.iter_encode`.

        :return: An ElementTree's Element or a list containing a sequence of ElementTree's \
        elements if the argument *path* matches multiple XML data chunks. If *validation* \
        argument is 'lax' a 2-items tuple is returned, where the first item is the encoded \
        object and the second item is a list containing the errors.
        """
        data, errors = [], []
        result: Union[ElementType, XMLSchemaValidationError]
        for result in self.iter_encode(obj, path, validation, *args, **kwargs):
            if not isinstance(result, XMLSchemaValidationError):
                data.append(result)
            elif validation == 'lax':
                errors.append(result)
            elif validation == 'strict':
                raise result

        if not data:
            return (None, errors) if validation == 'lax' else None
        elif len(data) == 1:
            if errors:
                resource = XMLResource(data[0])
                for e in errors:
                    e.source = resource

            return (data[0], errors) if validation == 'lax' else data[0]
        else:
            return (data, errors) if validation == 'lax' else data

    to_etree = encode


class XMLSchema10(XMLSchemaBase):
    """
    XSD 1.0 schema class.

    <schema
      attributeFormDefault = (qualified | unqualified) : unqualified
      blockDefault = (#all | List of (extension | restriction | substitution))  : ''
      elementFormDefault = (qualified | unqualified) : unqualified
      finalDefault = (#all | List of (extension | restriction | list | union))  : ''
      id = ID
      targetNamespace = anyURI
      version = token
      xml:lang = language
      {any attributes with non-schema namespace . . .}>
      Content: ((include | import | redefine | annotation)*, (((simpleType | complexType | group |
      attributeGroup) | element | attribute | notation), annotation*)*)
    </schema>
    """
    meta_schema = os.path.join(SCHEMAS_DIR, 'XSD_1.0/XMLSchema.xsd')  # type: ignore
    BASE_SCHEMAS = {
        XML_NAMESPACE: os.path.join(SCHEMAS_DIR, 'XML/xml_minimal.xsd'),
        XSI_NAMESPACE: os.path.join(SCHEMAS_DIR, 'XSI/XMLSchema-instance_minimal.xsd'),
    }


class XMLSchema11(XMLSchemaBase):
    """
    XSD 1.1 schema class.

    <schema
      attributeFormDefault = (qualified | unqualified) : unqualified
      blockDefault = (#all | List of (extension | restriction | substitution)) : ''
      defaultAttributes = QName
      xpathDefaultNamespace = (anyURI | (##defaultNamespace | ##targetNamespace| ##local)) : ##local
      elementFormDefault = (qualified | unqualified) : unqualified
      finalDefault = (#all | List of (extension | restriction | list | union))  : ''
      id = ID
      targetNamespace = anyURI
      version = token
      xml:lang = language
      {any attributes with non-schema namespace . . .}>
      Content: ((include | import | redefine | override | annotation)*,
      (defaultOpenContent, annotation*)?, ((simpleType | complexType |
      group | attributeGroup | element | attribute | notation), annotation*)*)
    </schema>

    <schema
      attributeFormDefault = (qualified | unqualified) : unqualified
      blockDefault = (#all | List of (extension | restriction | substitution))  : ''
      elementFormDefault = (qualified | unqualified) : unqualified
      finalDefault = (#all | List of (extension | restriction | list | union))  : ''
      id = ID
      targetNamespace = anyURI
      version = token
      xml:lang = language
      {any attributes with non-schema namespace . . .}>
      Content: ((include | import | redefine | annotation)*, (((simpleType | complexType | group |
      attributeGroup) | element | attribute | notation), annotation*)*)
    </schema>
    """
    meta_schema = os.path.join(SCHEMAS_DIR, 'XSD_1.1/XMLSchema.xsd')  # type: ignore
    XSD_VERSION = '1.1'

    BASE_SCHEMAS = {
        XML_NAMESPACE: os.path.join(SCHEMAS_DIR, 'XML/xml_minimal.xsd'),
        XSI_NAMESPACE: os.path.join(SCHEMAS_DIR, 'XSI/XMLSchema-instance_minimal.xsd'),
        XSD_NAMESPACE: os.path.join(SCHEMAS_DIR, 'XSD_1.1/xsd11-extra.xsd'),
        VC_NAMESPACE: os.path.join(SCHEMAS_DIR, 'VC/XMLSchema-versioning.xsd'),
    }

    xsd_complex_type_class = Xsd11ComplexType
    xsd_attribute_class = Xsd11Attribute
    xsd_any_attribute_class = Xsd11AnyAttribute
    xsd_group_class = Xsd11Group
    xsd_element_class = Xsd11Element
    xsd_any_class = Xsd11AnyElement
    xsd_atomic_restriction_class = Xsd11AtomicRestriction
    xsd_union_class = Xsd11Union
    xsd_key_class = Xsd11Key
    xsd_keyref_class = Xsd11Keyref
    xsd_unique_class = Xsd11Unique


XMLSchema = XMLSchema10
"""The default class for schema instances."""
