from jshandler import JackSessionHandler, Connection, Port, Session
import time


class TestConnection(object):
    
    def test_get_connections(self):
        jsh = JackSessionHandler()
        connections = jsh.session.get_connections()
        assert len(connections) > 0
        for c in connections:
            assert c.from_port.name and c.to_port.name
            
    def test_connect_disconnect(self):
        jsh = JackSessionHandler()
        out_port = jsh.session.get_port_by_name('system:playback_4')
        assert out_port
        assert out_port.is_output()
        
        inp_port = jsh.session.get_port_by_name('system:capture_4')
        assert inp_port
        assert inp_port.is_input()
        
        connection = Connection()
        connection.add_port(out_port)
        assert connection.to_port is not None and connection.from_port is None

        connection.add_port(inp_port)
        assert connection.to_port is not None and connection.from_port is not None

        assert not jsh.connection_exists(connection)
        assert jsh.connect(connection)

        time.sleep(2)
        assert jsh.connection_exists(connection)        
        assert jsh.disconnect(connection)
        time.sleep(2)
        assert not jsh.connection_exists(connection)

    def test_aliases(self):
        jsh = JackSessionHandler()
        ports = jsh.session.get_ports()
        aliases_found = False
        for port in ports:
            if port.alsa_name:
                assert port.alsa_name in port.aliases
                aliases_found = True
        assert aliases_found

    def test_regexp(self):
        jsh = JackSessionHandler()
        port = jsh.session.get_port_by_name('sys*')
        assert port is not None

