# -*- coding: utf-8 -*-

import autopath
import glob
from pyeole.pkg import EolePkg, PackageNotFoundError
from os import unlink
import apt

from pytest import raises

repo = None
mode = None
fakepkg = 'eole-fake'

def setup_module(module):
    try:
        #module.repo = EolePkg("apt", test=True)
        module.repo = EolePkg("apt")
        module.mode = "apt"
        # load cache
        module.repo.pkgmgr._load_apt_cache()
    except ImportError:
        try:
            module.repo = EolePkg("yum", test=True)
            module.mode = "yum"
        except ImportError:
            raise ImportError("No package manager module found")

def test_import():
    assert mode != None

def test_create_package_manager():
    assert isinstance(repo, EolePkg)

def test_update():
    """
    test apt-get update
    """
    #repo.update(container='root')
    pass

def test_get_existing_package():
    """
    search existant package
    """
    pkgname = fakepkg
    pkg = repo.get_package(pkgname)
    if mode == "apt":
        assert isinstance(pkg, apt.Package)
    elif mode == "yum":
        assert isinstance(pkg, yum.Package)

def test_get_nonexistant_package():
    """
    search non existant package
    """
    pkgname = "nonexistent"
    with raises(PackageNotFoundError):
        pkg = repo.get_package(pkgname)

def test_download():
    """
    download one package into a specific destination
    """
    repo.download(fakepkg, dest=u'/tmp')
    binary = glob.glob('/tmp/{0}*'.format(fakepkg))
    assert len(binary) == 1
    unlink(binary[0])

def test_fetch():
    """
    download one package into apt cache
    """
    repo.fetch_archives(fakepkg, container='root')
    binary = glob.glob('/var/cache/apt/archives/{0}*'.format(fakepkg))
    assert len(binary) == 1
    unlink(binary[0])

def test_install():
    """
    install a package
    """
    pkgname = fakepkg
    #repo.pkgmgr.set_test_run(True)
    repo.install(pkgname)
    repo.pkgmgr.cache.open()
    pkg = repo.get_package(pkgname)
    assert pkg.is_installed

def test_remove():
    """
    remove a package
    """
    pkgname = fakepkg
    #repo.pkgmgr.set_test_run(True)
    repo.remove(pkgname)
    repo.pkgmgr.cache.open()
    pkg = repo.get_package(pkgname)
    assert not pkg.is_installed

# do we really want to upgrade ???
##def test_upgrade():
##   repo.pkgmgr.set_test_run(True)
##    repo.upgrade()

#FIXME: doesn't work on EOLE 2.5 (#10705)
#def test_get_depends():
#    pkgname = "libc6"
#    deps = ['libc-bin', 'libgcc1', 'tzdata']
#    dp_list = repo.get_depends(pkgname)
#    assert dp_list == deps
