"""
<Filename>
  factoids/__init__.py

<Purpose>
  Used to print saesh factoids.
  
  It implements the following command:  
    show factoids [number of factoids]/all

"""

import seash_exceptions

import random
import os


# List which will contain all factoids after fatching from a file.
factoids = []


def initialize():
  """
  <Purpose>
    Used to print random seash factoid when user runs seash.
    
  <Arguments>
    None
    
  <Side Effects>
    Prints random factoid onto the screen.
    
  <Exceptions>
    UserError: Error during generating path to "factoid.txt" file or
               Error while opening, reading or closing "factoid.txt" file.
    
  <Return>
    None
  """
  
  # Global 'factoids' list will be used to store factoids, fetched from a file.
  global factoids
  
  # Path to "factoid.txt" file is created.
  try:
    current_path = os.getcwd()
    file_path = os.path.join(current_path, "modules", "factoids", "factoid.txt")
  except OSError, error:
    raise seash_exceptions.InitializeError("Error during initializing factoids module: '" + str(error) + "'.")

  # We have to fatch list of factoids from "factoid.txt" file.
  try:
    file_object = open(file_path, 'r')
    factoids_temp = file_object.readlines()
    file_object.close()
  except IOError, error:
    raise seash_exceptions.InitializeError("Error during initializing factoids module: '" + str(error) + "'.")
  
  # Newline characters in a list, read from a file are removed.
  for factoid in factoids_temp:
    factoids.append(factoid.strip('\n'))
  
  # A random factoid is printed every time user runs seash.
  print random.choice(factoids)+"\n"


def cleanup():
  """
  <Purpose>
    Used to clean 'factoids' list when this module is going to be disabled.
    
  <Arguments>
    None
    
  <Side Effects>
    None
    
  <Exceptions>
    None
    
  <Return>
    None
  """
  
  # Data from a global 'factoids' list will be removed.
  global factoids
  factoids = []


def print_factoids(input_dict, environment_dict):
  """
  <Purpose>
    Used to print seash factoids when user uses 'show factoids'
    command.
    
  <Arguments>
    input_dict: Input dictionary generated by seash_dictionary.parse_command().
    environment_dict: Dictionary describing the current seash environment.
    
    For more information, see command_callbacks.py's module docstring.
    
  <Side Effects>
    Prints factoids onto the screen.
    
  <Exceptions>
    UserError: If user does not type appropriate command.
    ValueError: If user does not provide valid input (integer).
    
  <Return>
    None
  """
  
  # User will insert an argument regarding how many factoids should be printed.
  # We have to find what is user argument.
  # User can type any positive number or he can type 'all' to see all factoids.
  dict_mark = input_dict
  try:
    command = dict_mark.keys()[0]
    while dict_mark[command]['name'] != 'args':
      dict_mark = dict_mark[command]['children']
      command = dict_mark.keys()[0]
    args = command
  except IndexError:
    raise seash_exceptions.UserError("\nError, Syntax of the command is: show factoids [number of factoids]/all \n")
  
  # User decided to print all factoids
  if args == 'all':
    print
    for factoid in factoids:
      print factoid
    print
    return
  
  # User can not insert other than integer number.
  try:
    no_of_factoids = int(args)
  except ValueError:
    raise seash_exceptions.UserError("\nYou have to enter number only.\n")
  
  # If number of factoids decided by user is greater than total number of
  # available factoids than whole factoids list is printed.
  if (no_of_factoids > (len(factoids))):
    print "\nWe have only %d factoids. Here is the list of factoids:" % (len(factoids))
    no_of_factoids = len(factoids)
  elif (no_of_factoids <= 0):
    raise seash_exceptions.UserError("\nYou have to enter positive number only.\n")
  
  # 'factoids' list will be shuffled every time for printing random factoids.
  random.shuffle(factoids)
  
  # Factoids will be printed.
  for factoid in factoids[:no_of_factoids]:
    print factoid
  print
  



command_dict = {
  'show': {'name':'show', 'callback': None, 'children':{
      'factoids':{'name':'factoids', 'callback': print_factoids,
                  'summary': "Displays available seash factoids.",
                  'help_text': '','children':{
          '[ARGUMENT]':{'name':'args', 'callback': None, 'children':{}}
    }},}}
}



help_text = """
Factoids Module

This module includes command that prints seash factoids.
'show factoids [number of factoids]/all' is used to print
available seash factoids.
You can type 'show factoids [number of factoids]' to print
that much number of factoids.
You can type 'show factoids all' to see all available factoids.
"""


# This is where the module importer loads the module from.
moduledata = {
  'command_dict': command_dict,
  'help_text': help_text,
  'url': None,
  'initialize': initialize,
  'cleanup': cleanup
}