#!/usr/bin/python3
"""Test pathlib's handling of Unicode strings."""

from __future__ import print_function

import errno
import pkg_resources
import shutil
import sys
import tempfile

from typing import Any, Type

assert sys.version_info[0] in (2, 3), sys.version_info
PY2 = sys.version_info[0] < 3

if PY2:
    import pathlib2 as pathlib
else:
    import pathlib


def examine_path(path, name, name_type=str):
    # type: (pathlib.Path, str, Type[Any]) -> None
    """Examine an already-build path."""
    print("\nExamining {path}".format(path=path))
    print(repr(path))
    print(repr(path.name))
    print(repr(path.parts))
    assert path.name == name
    assert isinstance(path.name, name_type)
    assert all(isinstance(part, str) for part in path.parts[:-1])
    assert path.parts[-1] == name
    assert isinstance(path.parts[-1], name_type)
    print("")


def main():
    # type: () -> None
    """Create a path from disjoint parts, test it."""
    print("PY2: {py2}".format(py2=PY2))

    if PY2:
        pathver = pkg_resources.Environment()["pathlib2"][0].parsed_version
        # It seems that the packaging module hides its version submodule, so...
        Version = type(pathver)
        assert pathver >= Version("2")
        v235 = pathver <= Version("2.3.5")
    else:
        v235 = False

    tempd = None
    try:
        tempd = tempfile.mkdtemp(prefix="pathlib-test.")
        print("Using temporary directory {tempd}".format(tempd=tempd))
        tempd_etc_b = str(tempd).encode("UTF-8") + b"/etc"

        print("init")
        base = pathlib.Path(tempd_etc_b.decode("UTF-8"))
        examine_path(base, "etc")

        print(".absolute()")
        base_abs = base.absolute()
        examine_path(base.absolute(), "etc")

        print(".anchor")
        assert isinstance(base.anchor, str)
        print("")

        print(".glob()")
        base.mkdir(mode=0o755)
        (base / "a.file").write_bytes(b"")
        first_child = next(base.glob(b"*".decode("us-ascii")))
        examine_path(first_child, "a.file")

        print(".__div__() / .__truediv__()")
        child = base / b"passwd".decode("UTF-8")
        examine_path(child, "passwd")

        print(".joinpath()")
        child = base.joinpath(b"passwd".decode("ISO-8859-1"))
        examine_path(child, "passwd")

        print(".match()")
        assert child.match(b"*ssw*".decode("us-ascii"))
        print("")

        print(".parent()")
        examine_path(child.parent, "etc")

        print(".parents()")
        for parent in child.parents:
            if str(parent) != "/":
                examine_path(parent, parent.name)

        print(".relative_to()")
        rel = child.relative_to(str(parent).encode("UTF-8").decode("UTF-8"))
        examine_path(rel, "passwd")

        print("rename()")
        try:
            first_child.rename(b"/nonexistent/nah".decode("us-ascii"))
        except OSError as err:
            if err.errno not in (errno.ENOENT, errno.ENOTDIR):
                raise
        print("")

        if sys.version_info >= (3, 3):
            print("replace()")
            try:
                first_child.replace(b"/nonexistent/nah".decode("us-ascii"))
            except OSError as err:
                if err.errno not in (errno.ENOENT, errno.ENOTDIR):
                    raise
            print("")

        print(".rglob()")
        first_child = next(base.rglob(b"*".decode("us-ascii")))
        examine_path(first_child, "a.file")

        print(".root")
        assert isinstance(child.root, str)
        print("")

        print(".samefile()")
        assert not first_child.samefile(str(__file__).encode("UTF-8").decode("UTF-8"))
        print("")

        print(".stem")
        assert isinstance(child.stem, str)
        print("")

        print(".suffix")
        assert isinstance(child.suffix, str)
        print("")

        print(".suffixes")
        assert all(isinstance(suffix, str) for suffix in child.suffixes)
        print("")

        print(".symlink_to()")
        assert not child.exists()
        child.symlink_to(b"a.file".decode("us-ascii"))
        assert child.samefile(first_child)
        print("")

        print(".with_name()")
        child = child.with_name(b"hosts".decode("us-ascii"))
        if PY2 and v235:
            # Oops... https://github.com/ppentchev/pathlib2/commit/a75493d48d971ad5f0858abb25c7e6598deb560f
            examine_path(child, "hosts", name_type=unicode)
        else:
            examine_path(child, "hosts")

        print(".with_suffix()")
        child = child.with_suffix(b".txt".decode("us-ascii"))
        if PY2 and v235:
            # Oops... https://github.com/ppentchev/pathlib2/commit/a75493d48d971ad5f0858abb25c7e6598deb560f
            examine_path(child, "hosts.txt", name_type=unicode)
        else:
            examine_path(child, "hosts.txt")

        print("It all passed... with prejudice.")
    finally:
        if tempd is not None:
            print("Cleaning up the temporary directory {tempd}".format(tempd=tempd))
            shutil.rmtree(tempd)


if __name__ == "__main__":
    main()
