#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright (C) 2010-2015 by Mike Gabriel <mike.gabriel@das-netzwerkteam.de>
#
# Python X2Go is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# Python X2Go is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.

###
### short example for python-phoca usage
###

# import x2go before you import other thread based modules (e.g. paramiko)
import x2go

import gevent
import getpass
import threading

# modify to your needs...
server   = "server.mydomain.tld"
port     = 22
username = "foo"
command  = "XFCE"

def my_progress_bar(ps):

    for status in ps:
        print '---------------'
        print 'SESSION STATUS: ' + '#' * status + "(" + str(status) + "%%)"
        print '---------------'

password = getpass.getpass()

cli = x2go.X2GoClient(use_cache=False, loglevel=x2go.log.loglevel_DEBUG)
s_uuid = cli.register_session(server, port=port,
                              username=username,
                              cmd=command,
                              add_to_known_hosts=True,
                             )
cli.connect_session(s_uuid, password=password)

# clean sessions and check the result
cli.clean_sessions(s_uuid)

# initialize a ProgressStatus event and iterator
progress_event = threading.Event()
progress_status = x2go.utils.ProgressStatus(progress_event, cli.get_session(s_uuid).get_progress_status)

# start the status bar
gevent.spawn(my_progress_bar, progress_status)

# start the session
gevent.spawn(cli.start_session, s_uuid, progress_event=progress_event)

# wait long enough for session to come up completely
while (cli.get_session(s_uuid).get_progress_status() < 100) and (cli.get_session(s_uuid).get_progress_status() != -1):
    gevent.sleep(1)

try:
    while cli.session_ok(s_uuid):
        gevent.sleep(2)
except KeyboardInterrupt:
    pass

# suspend the session
cli.suspend_session(s_uuid)
