# Path: pypot/server/snap.py
# def find_local_ip(host=None):
#     # see here: http://stackoverflow.com/questions/166506/
#     try:
#         if host is None:
#             host = socket.gethostname()
# 
#         if 'local' not in host:
#             host += '.local'
# 
#         try:
#             ips = [ip for ip in socket.gethostbyname_ex(host)[2]
#                    if not ip.startswith('127.')]
#             if len(ips):
#                 return ips[0]
#         except socket.gaierror:
#             logger.debug('socket gaierror with hostname {}'.format(host))
#             pass
# 
#         # If the above method fails (depending on the system)
#         # Tries to ping google DNS instead (need a internet connexion)
#         try:
#             with closing(socket.socket()) as s:
#                 s.settimeout(1)
#                 s.connect(('8.8.8.8', 53))
#                 return s.getsockname()[0]
#         except socket.timeout:
#             logger.debug('socket timeout')
#             pass
# 
#     except IOError as e:
#         # network unreachable
#         # error no 10065 = WSAESERVERUNREACH Windows Network unreachable
#         if e.errno == errno.ENETUNREACH or e.errno == 10065:
#             logger.debug('network unreachable')
#             pass
#         else:
#             raise
#     return '127.0.0.1'
# 
# Path: pypot/utils/flushed_print.py
# def flushed_print(*args, **kwargs):
#     """
#     Use to replace print(*args, flush=True) that doesn't exist for python<3.3
#     """
#     print(*args, **kwargs)
#     file = kwargs.get('file', sys.stdout)
#     file.flush() if file is not None else sys.stdout.flush()


import os
import sys
import time
import random
import logging
import argparse
import webbrowser
from contextlib import closing
from argparse import RawTextHelpFormatter
from pypot.server.snap import find_local_ip
from pypot.creatures import installed_poppy_creatures
from pypot.utils import flushed_print as print
from multiprocessing import Process
from http.server import HTTPServer
from http.server import SimpleHTTPRequestHandler
		from pypot.vpl.scratch import download_scratch_interactively
		from pypot.vpl.snap import download_snap_interactively
			scratch_static_server_started = True
			scratch_static_server_process.start()

			scratch_url = 'http://127.0.0.1:{}/'.format(scratch_static_port)
			url = '{}'.format(scratch_url)

	snap_static_server_started = False
	if args.snap and not args.no_browser:
		snap_static_port = 8888
		snap_static_server = HTTPServer(("0.0.0.0", snap_static_port), SimpleHTTPRequestHandler)

		static_app = download_snap_interactively()
		if static_app is None:
			print("The static server was not started because the VPL app has not been downloaded")
		else:
			os.chdir(static_app)
			snap_static_server_process = Process(target=snap_static_server.serve_forever, args=())
			snap_static_server_started = True
			snap_static_server_process.start()

			snap_url = 'http://127.0.0.1:{}/snap.html'.format(snap_static_port)
			block_url = 'http://{}:{}/snap-blocks.xml'.format(
				find_local_ip(), args.snap_port)
			url = '{}#open:{}'.format(snap_url, block_url)

	with closing(start_poppy_with_services(args)):

		msg = ''

		if args.dummy or args.poppy_simu:

# Path: pypot/server/snap.py
# def find_local_ip(host=None):
#     # see here: http://stackoverflow.com/questions/166506/
#     try:
#         if host is None:
#             host = socket.gethostname()
# 
#         if 'local' not in host:
#             host += '.local'
# 
#         try:
#             ips = [ip for ip in socket.gethostbyname_ex(host)[2]
#                    if not ip.startswith('127.')]
#             if len(ips):
#                 return ips[0]
#         except socket.gaierror:
#             logger.debug('socket gaierror with hostname {}'.format(host))
#             pass
# 
#         # If the above method fails (depending on the system)
#         # Tries to ping google DNS instead (need a internet connexion)
#         try:
#             with closing(socket.socket()) as s:
#                 s.settimeout(1)
#                 s.connect(('8.8.8.8', 53))
#                 return s.getsockname()[0]
#         except socket.timeout:
#             logger.debug('socket timeout')
#             pass
# 
#     except IOError as e:
#         # network unreachable
#         # error no 10065 = WSAESERVERUNREACH Windows Network unreachable
#         if e.errno == errno.ENETUNREACH or e.errno == 10065:
#             logger.debug('network unreachable')
#             pass
#         else:
#             raise
#     return '127.0.0.1'
# 
# Path: pypot/utils/flushed_print.py
# def flushed_print(*args, **kwargs):
#     """
#     Use to replace print(*args, flush=True) that doesn't exist for python<3.3
#     """
#     print(*args, **kwargs)
#     file = kwargs.get('file', sys.stdout)
#     file.flush() if file is not None else sys.stdout.flush()


# Path: pypot/creatures/services_launcher.py
import os
import sys
import time
import random
import logging
import argparse
import webbrowser
from contextlib import closing
from argparse import RawTextHelpFormatter
from pypot.server.snap import find_local_ip
from pypot.creatures import installed_poppy_creatures
from pypot.utils import flushed_print as print
from multiprocessing import Process
from http.server import HTTPServer
from http.server import SimpleHTTPRequestHandler
		from pypot.vpl.scratch import download_scratch_interactively
		from pypot.vpl.snap import download_snap_interactively

			scratch_static_server_started = True
			scratch_static_server_process.start()

			scratch_url = 'http://127.0.0.1:{}/'.format(scratch_static_port)
			url = '{}'.format(scratch_url)

	snap_static_server_started = False
	if args.snap and not args.no_browser:
		snap_static_port = 8888
		snap_static_server = HTTPServer(("0.0.0.0", snap_static_port), SimpleHTTPRequestHandler)

		static_app = download_snap_interactively()
		if static_app is None:
			print("The static server was not started because the VPL app has not been downloaded")
		else:
			os.chdir(static_app)
			snap_static_server_process = Process(target=snap_static_server.serve_forever, args=())
			snap_static_server_started = True
			snap_static_server_process.start()

			snap_url = 'http://127.0.0.1:{}/snap.html'.format(snap_static_port)
			block_url = 'http://{}:{}/snap-blocks.xml'.format(
				find_local_ip(), args.snap_port)
			url = '{}#open:{}'.format(snap_url, block_url)

	with closing(start_poppy_with_services(args)):

		msg = ''

		if args.dummy or args.poppy_simu:

			msg += 'Simulated robot created! He is running on: ip={}'.format(find_local_ip())