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

import globalv, tcpserver, tcpsender, xmppserver, logger, SocketServer, sys
import thread, traceback, net
from buddies import Contacts

"""helper functions called by main.py"""

def start_all():
    """starts all murrayb-functions"""
    #logfile
    logfile = globalv.GLOBAL_LOG
    #starting local jabberserver
    if globalv.SUPERNODE:
        pass
    else:
        print 'Restoring Buddylist'
        Contacts().load(globalv.CLIST_FILE)
        print 'Starting local XMPP-Server on port', globalv.XMPPPORT
        globalv.XMPPSERVER = SocketServer.TCPServer(('', int(globalv.XMPPPORT)), \
        xmppserver.MurrayXMPPServer)
        thread.start_new_thread(globalv.XMPPSERVER.serve_forever, ())
        print 'done'
    if globalv.PROTO == 'tcp':
        print 'Bringing up external Murray-TCP server on Port ' + str(globalv.PORT)
        globalv.TCPSERVER = SocketServer.ThreadingTCPServer(('',int(globalv.PORT)), \
        tcpserver.MurrayTCPServer)
        try:
            thread.start_new_thread(globalv.TCPSERVER.serve_forever, ())
        except SystemExit:
            pass
        thread.start_new_thread(tcpsender.resend, ())
        print 'TCP Server running'
    else:
        print '''Currently, I can only speak TCP/IP. Want something else? 
        Start programming!'''
        sys.exit(1)
    import net
    # get some info on the net
    net.bootstrap(5)
    
    print 'starting known peers management'
    thread.start_new_thread(net.updateKnownPeers, ())
    thread.start_new_thread(net.sir_pingALot, ())
    
"""FIXME: Nach net.py verschieben!!!!        
		
def dsl_user(new_ip):
	sends all known peers information over a changed IP-address
	global IP 
	IP = new_ip
	kp = cache.knownPeers().getAllMurray_IDs()
	p2p = net.Peer2Peer()
	for uid in kp:
		thread.start_new_thread(p2p.sendhello, (uid, 0))  """
        

    
class Running:
    def __init__(self):
        start_all()
        while globalv.RUNNING:
            input = raw_input('>>> ')
            input = input.split()
            func = input[0]
            args = tuple(input[1:])
            try:
                f = getattr(self, func)
                f(args)
            except AttributeError:
                self.help()
            except SystemExit:
                pass
    def shutdown(self, *args):
            try:
                globalv.RUNNING = False
                print 'shutting down...'
                print 'saving known peers and contact list'
                net.shutdown()
                Contacts().store(globalv.CLIST_FILE)
                globalv.SHOW = 'unavailable'
                print 'stopping local XMPP-Server'
                globalv.XMPPSERVER.server_close()
                print 'stopping external murray server'
                globalv.TCPSERVER.server_close()
            except:
                logger.write((str(sys.exc_type) + str(sys.exc_value) + \
        str(traceback.extract_tb(sys.exc_traceback)) + '\n'))
            finally:
                logger.close()
                print 'bye'
            
    def help(*args):
        info = """Available Options: \n\n
        help -- print this help \n
        shutdown -- exit gracefully"""
        print info