# Copyright (c) 2016 Iotic Labs Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://github.com/Iotic-Labs/py-IoticAgent/blob/master/LICENSE
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Python 2.7 & 3.2/3.3 compatibility"""

# pylint: disable=unused-import,invalid-name,import-error,undefined-variable,ungrouped-imports,no-name-in-module
# pylint: disable=wrong-import-order

from __future__ import unicode_literals

from sys import version_info
from keyword import kwlist
from warnings import warn

PY3 = (version_info[0] == 3)


try:
    import regex as _regex
    from regex import compile as re_compile  # noqa (unused import)
    # Force re module compatible behaviour
    _regex.DEFAULT_VERSION = _regex.V0
except ImportError:
    from re import compile as re_compile  # noqa (unused import)
    warn('Unable to import regex - falling back to re module', ImportWarning)


# PY3K
if PY3:  # noqa (complexity)
    from queue import Queue, Empty, Full  # noqa (unused import)
    from threading import Lock, RLock, Event  # noqa (unsed import)
    from urllib.parse import urlparse
    SocketError = OSError  # noqa (unused import)

    string_types = str
    unicode_type = str
    int_types = (int,)
    number_types = (int, float)

    def u(obj):
        """Casts obj to unicode string, unless already one"""
        return obj if isinstance(obj, str) else str(obj)

    def ensure_ascii(obj, name=None):
        """Checks whether obj is an ascii string. For Python 2 only also decodes plain (old) str objects"""
        if isinstance(obj, str):
            try:
                obj.encode('ascii')
            except:
                pass
            else:
                return obj
        raise ValueError('%s not a valid (ascii) string' % (name if name else 'Argument'))

    def ensure_unicode(obj, name=None):
        """Checks whether obj is a unicode string. For Python 2 only also decodes plain (old) str objects"""
        if isinstance(obj, str):
            return obj