# -*- coding: utf-8 -*-
# :-
# :Copyright: (c) 2015-2021, Franz Glasner. All rights reserved.
# :License:   BSD-3-Clause. See LICENSE.txt for details.
# :-
"""Some minimal compatibility shim between Python2 and Python3

"""

from __future__ import division, absolute_import, print_function


__all__ = ["PY2",
           "text_to_native_os_str",
           "native_os_str_to_text",
           "u",
           "u2fs",
           "uchr"]


import sys
import os
import locale


PY2 = sys.version_info[0] <= 2


if PY2:

    _OS_ENCODING = locale.getpreferredencoding()

    _FS_ENCODING = sys.getfilesystemencoding() or _OS_ENCODING


    def text_to_native_os_str(s, encoding=None):
        if isinstance(s, unicode):                       # noqa: F821
            return s.encode(encoding or _OS_ENCODING)
        else:
            return s


    def native_os_str_to_text(s, encoding=None):
        return s.decode(encoding or _OS_ENCODING)


    def u(s, encoding="utf-8"):
        if isinstance(s, unicode):                       # noqa: F821
            return s
        else:
            return s.decode(encoding)


    def u2fs(s, force=False):
        """Convert a text (Unicode) string to the filesystem encoding.

        .. note:: The filesystem encoding on Python 3 is a Unicode text
                  string. The function is a noop when called on Python 3.

        .. note:: If `s` is already a byte string be permissive and
                  return `s` unchanged.

        """
        if isinstance(s, str):
            return s
        if not force and os.name in ("nt", "ce"):
            # WinNT and CE have native Unicode support: nothing to convert
            return s
        return s.encode(_FS_ENCODING)

    def uchr(n):
        return unichr(n)      # noqa: F821

else:

    def text_to_native_os_str(s, encoding=None):
        return s


    def native_os_str_to_text(s, encoding=None):
        return s


    def u(s, encoding="utf-8"):
        if isinstance(s, str):
            return s
        else:
            return s.decode(encoding)


    def u2fs(s, force=False):
        """Convert a text (Unicode) string to the filesystem encoding.

        .. note:: The filesystem encoding on Python 3 is a Unicode text
                  string. The function is a noop when called on Python 3.

        .. note:: If `s` is already a byte string be permissive and
                  return `s` unchanged.

        """
        assert isinstance(s, str)
        return s

    def uchr(n):
        return chr(n)
