# 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
	parser.add_argument('--ws-port',
						help='port of Websocket Server',
						default=9009, type=int)
	parser.add_argument('--disable-camera',
						help='Start the robot without the camera.',
						action='store_true')
	parser.add_argument('-v', '--verbose',
						help='start services with verbose mode. There is 3 debug levels, add as "v" as debug level you want',
						action='count')
	parser.add_argument('-f', '--log-file',
						help='Log filename',
						action='store')

	nb_creatures = len(installed_poppy_creatures.keys())
	if nb_creatures == 0:
		print('No installed poppy creature were found!')
		print('You should first install the python package '
			  'corresponding to your robot or check your python environment.')
		sys.exit(1)

	args = parser.parse_args()

	# If no creature are specified and only one is installed
	# We use it as default.
	if args.creature is None:
		if nb_creatures > 1:
			parser.print_help()
			sys.exit(1)

		args.creature = list(installed_poppy_creatures.keys())[0]

# 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

	parser.add_argument('--ws-port',
						help='port of Websocket Server',
						default=9009, type=int)
	parser.add_argument('--disable-camera',
						help='Start the robot without the camera.',
						action='store_true')
	parser.add_argument('-v', '--verbose',
						help='start services with verbose mode. There is 3 debug levels, add as "v" as debug level you want',
						action='count')
	parser.add_argument('-f', '--log-file',
						help='Log filename',
						action='store')

	nb_creatures = len(installed_poppy_creatures.keys())
	if nb_creatures == 0:
		print('No installed poppy creature were found!')
		print('You should first install the python package '
			  'corresponding to your robot or check your python environment.')
		sys.exit(1)

	args = parser.parse_args()

	# If no creature are specified and only one is installed
	# We use it as default.
	if args.creature is None:
		if nb_creatures > 1:
			parser.print_help()
			sys.exit(1)

		args.creature = list(installed_poppy_creatures.keys())[0]

		print('No creature specified, use {}'.format(args.creature))