import os
import platform
import shutil
import tarfile
import tempfile

import time
from six import BytesIO

from conans.client.tools.files import untargz
from conans.client.tools.win import get_cased_path
from conans.errors import ConanException
from conans.paths import PACKAGE_TGZ_NAME
from conans.test import CONAN_TEST_FOLDER
from conans.util.files import gzopen_without_timestamps


def wait_until_removed(folder):
    latest_exception = None
    for _ in range(50):  # Max 5 seconds
        time.sleep(0.1)
        try:
            shutil.rmtree(folder)
            break
        except Exception as e:
            latest_exception = e
    else:
        raise Exception("Could remove folder %s: %s" % (folder, latest_exception))


def temp_folder(path_with_spaces=True, create_dir=True):
    t = tempfile.mkdtemp(suffix='conans', dir=CONAN_TEST_FOLDER)
    # Make sure that the temp folder is correctly cased, as tempfile return lowercase for Win
    t = get_cased_path(t)
    # necessary for Mac OSX, where the temp folders in /var/ are symlinks to /private/var/
    t = os.path.realpath(t)
    # FreeBSD and Solaris do not use GNU Make as a the default 'make' program which has trouble
    # with spaces in paths generated by CMake
    if not path_with_spaces or platform.system() == "FreeBSD" or platform.system() == "SunOS":
        path = "pathwithoutspaces"
    else:
        path = "path with spaces"
    nt = os.path.join(t, path)
    if create_dir:
        os.makedirs(nt)
    return nt


def uncompress_packaged_files(paths, pref):
    rev = paths.get_last_revision(pref.ref).revision
    prev = paths.get_last_package_revision(pref.copy_with_revs(rev, None)).revision
    pref = pref.copy_with_revs(rev, prev)

    package_path = paths.package(pref)
    if not(os.path.exists(os.path.join(package_path, PACKAGE_TGZ_NAME))):
        raise ConanException("%s not found in %s" % (PACKAGE_TGZ_NAME, package_path))
    tmp = temp_folder()
    untargz(os.path.join(package_path, PACKAGE_TGZ_NAME), tmp)
    return tmp


def scan_folder(folder):
    scanned_files = []
    for root, dirs, files in os.walk(folder):
        dirs[:] = [d for d in dirs if d != "__pycache__"]
        relative_path = os.path.relpath(root, folder)
        for f in files:
            if f.endswith(".pyc"):
                continue
            relative_name = os.path.normpath(os.path.join(relative_path, f)).replace("\\", "/")
            scanned_files.append(relative_name)

    return sorted(scanned_files)


def tgz_with_contents(files):
    folder = temp_folder()
    file_path = os.path.join(folder, "myfile.tar.gz")

    with open(file_path, "wb") as tgz_handle:
        tgz = gzopen_without_timestamps("myfile.tar.gz", mode="w", fileobj=tgz_handle)

        for name, content in files.items():
            info = tarfile.TarInfo(name=name)
            data = content.encode('utf-8')
            info.size = len(data)
            tgz.addfile(tarinfo=info, fileobj=BytesIO(data))

        tgz.close()

    return file_path
