from globals import *

import alife

import logging
import random
import os

def prettify_string_array(array, max_length):
	"""Returns a human readable string from an array of strings."""
	_string = ''
	
	_i = 0
	for entry in array:
		if len(_string) > max_length:
			_string += ', and %s more.' % (_i+1)
			
			break
		
		if _i == 0:
			_string += entry
		elif 0<_i<len(array)-1:
			_string += ', %s' % entry
		elif _i == len(array)-1:
			_string += ' and %s.' % entry
		
		_i += 1
	
	return _string

def get_name(life):
	return ' '.join(life['name'])

def get_real_direction(direction, short=False):
	if abs(direction)<22 or abs(direction-360)<22:
		if short:
			return 'e'
		
		return 'east'
	elif abs(direction-45)<22:
		if short:
			return 'ne'
		
		return 'northeast'
	elif abs(direction-90)<22:
		if short:
			return 'n'
		
		return 'north'
	elif abs(direction-135)<22:
		if short:
			return 'nw'
		
		return 'northwest'
	elif abs(direction-180)<22:
		if short:
			return 'w'
		
		return 'west'
	elif abs(direction-225)<22:
		if short:
			return 'sw'
		
		return 'southwest'
	elif abs(direction-270)<22:
		if short:
			return 's'
		
		return 'south'
	elif abs(direction-315)<22:
		if short:
			return 'se'
		
		return 'southeast'
	else:
		if short:
			return 'e'
		
		return 'east'

def get_real_distance(distance):
	"""Returns the real-life representation of a distance."""
	
	if SETTINGS['distance unit'] == 'Yards':
		return distance*YARDS
	else:
		return distance*METERS

def get_real_distance_string(distance, round_up=False):
	_distance = get_real_distance(distance)
	_mods = ''
	
	if round_up:
		_distance = int(round(_distance))
	
	if not _distance == 1:
		_mods = 's'
	
	if SETTINGS['distance unit'] == 'Yards':
		return '%s yd%s' % (_distance, _mods)
	
	return '%s m%s' % (_distance, _mods)

def get_name_ownership(life, pronoun=False):
	if pronoun:
		if life['type'] == 'humanoid':
			return 'his'
		else:
			return 'its'
	
	return '%s\'s' % ' '.join(life['name'])

def get_introduction(life, posession=False):
	if 'player' in life:
		if posession:
			return 'Your'
		
		return 'You'
	
	if life['type'] == 'humanoid':
		if posession:
			return '%s\'s' % get_name(life)
		else:
			return get_name(life)
	else:
		#TODO: Check limb conditions
		if posession:
			return 'The %s\'s' % life['species']
		else:
			return 'The %s' % life['species']

def _load_strings(a, directory, filenames):
	for filename in [f for f in filenames if f.count('.txt')]:
		_map_name = filename.strip('.txt')
		TEXT_MAP[_map_name] = []
		
		with open(os.path.join(directory, filename), 'r') as e:
			TEXT_MAP[_map_name].extend([line.strip() for line in e.readlines()])

def load_strings():
	#TODO: Use better walk, like one in profiles.py
	try:
		os.path.walk(TEXT_DIR, _load_strings, None)
		load_dialog()
	except Exception, e:
		raise Exception(e)