import os
import sys
from shlex import shlex
from syn.five import STR
from mock import MagicMock
from syn.base_utils import assign, capture
from depman.main import _main, main
import depman.apt as aptd
import depman.pip as pipd
from depman import Pip, Apt
from depman import __version__ as dver

#-------------------------------------------------------------------------------

DIR = os.path.dirname(os.path.abspath(__file__))
DEPS1 = os.path.join(DIR, 'deps1.yml')
DEPS6 = os.path.join(DIR, 'deps6.yml')
DEPSEX = os.path.join(DIR, 'examples/requirements.yml')
TEST1 = os.path.join(DIR, 'test1')

#-------------------------------------------------------------------------------

def test_main():
    def invoke(cmd):
        if  isinstance(cmd, STR):
            _main(*shlex.split(cmd))
        else:
            _main(*cmd)

    # Version
    with assign(sys, 'argv', ['', 'version']):
        with capture() as (out, err):
            main()
    assert out.getvalue() == 'depman {}\n'.format(dver)

    # Satisfy
    with assign(aptd, 'command', MagicMock()):
        with assign(pipd, 'command', MagicMock()):
            with assign(Pip, '_pkgs', dict(lxml='', PyYAML='')):
                with assign(Apt, '_pkgs', {'libxml2-dev': '',
                                          'libxslt1-dev': ''}):
                    invoke(['satisfy', '-f', DEPS1])
                    assert aptd.command.call_count == 0
                    assert pipd.command.call_count == 0

    # Validate
    with assign(aptd, 'command', MagicMock()):
        with assign(pipd, 'command', MagicMock()):
            with assign(Pip, '_pkgs', dict(lxml='', PyYAML='')):
                invoke(['validate', '-f', DEPS1])
                assert aptd.command.call_count == 0
                assert pipd.command.call_count == 0

    # Validate the example file(s)
    invoke(['validate', '-f', DEPSEX])

    # Export
    eout = '''# Auto-generated by depman 0.3.4
gevent<=1.0.2
numpy
openopt
six
syn>=0.0.14'''

    invoke(['export', 'prod', '-f', DEPSEX, '-t', 'pip', '-o', TEST1])
    with open(TEST1, 'rt') as f:
        assert f.read() == eout

    #Version
    invoke(['version'])

#-------------------------------------------------------------------------------
