"""
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the
Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Copyright 2004 Will Guaraldi
"""

__author__ = "Will Guaraldi <willg@bluesock.org>"
__version__ = "0.5"
__description__ = "Allows you to export help files using a script to a text file."

import os, time
from lyntin import exported, config, utils
from lyntin.modules import modutils

commands_dict = {}

def printhelp_cmd(ses, args, input):
  """
  Prints all the help topics available in a pretty tree.

  category: hacker
  """
  hm = exported.get_manager("help")
  hm._printTree()

commands_dict["printhelp"] = (printhelp_cmd, "")

def exporthelp_cmd(ses, args, input):
  """
  Uses templates to create a final document after filling in various
  help topics.

  %options:topic-name%

  Where options are:

    all - if the topic is actually a category, this will go through
          all the members of the category and throw them all in the
          file in order of topic name

    indent=n - indents the members of the category n number of spaces

  category: hacker
  """
  script = args["script"]
  outfile = args["outfile"]

  datadir = config.options["datadir"]
  if os.sep not in script:
    script = datadir + script

  if os.sep not in outfile:
    outfile = datadir + outfile

  try:
    f = open(script, "r")
    lines = f.readlines()
    f.close()
  except:
    exported.write_traceback("exporthelp: problem with opening script.")
    return

  try:
    f = open(outfile, "w")
  except:
    exported.write_traceback("exporthelp: problem with opening outfile.")
    return

  hm = exported.get_manager("help")

  for line in lines:
    linefixed = utils.chomp(line)
    if linefixed and linefixed[0] == "%" and linefixed[-1] == "%":
      nodename = linefixed[1:-1]

      if nodename == "date":
        f.write(time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()) + "\n")
        continue

      exported.write_message("exporthelp: fetching '%s'." % nodename)
      try:
        all = 0
        indent = 0
        listing = 0

        if nodename.find(":") != -1:
          options, nodename = nodename.split(":")
          options = options.split(",")
          for mem in options:
            if mem.find("all") != -1:
              all = 1
            elif mem.find("indent=") != -1:
              indent = int(mem[mem.find("=")+1:])
            elif mem.find("listing") != -1:
              listing = 1

        nodedata = hm.getNode(nodename)

        if nodedata[0]:
          f.write(nodedata[0] + "\n\n\n\n")

        if all == 1 and nodedata[1]:
          nodedata = nodedata[1]
          nodedata.sort()
          for mem in nodedata:
            nd2 = hm.getNode(mem)
            if nd2[0]:
              f.write(mem.upper() + "\n\n" + \
                      (indent * " ") + \
                      nd2[0].replace("\n", "\n" + (indent * " ")) + "\n\n\n\n")

        if listing == 1 and nodedata[1]:
          nodedata = nodedata[1]
          nodedata = [m.split(".")[-1] for m in nodedata]
          nodedata.sort()
          f.write(utils.columnize(nodedata, 70, indent) + "\n\n")

      except:
        exported.write_traceback("exporthelp: bad stuff with '%s'." % nodename)
        f.write(line)
    else:
      f.write(line)

  f.close()
  exported.write_message("exporthelp: succesfully built '%s'." % outfile)

commands_dict["exporthelp"] = (exporthelp_cmd, "script outfile")


def load():
  """ Initializes the module by binding all the commands."""
  modutils.load_commands(commands_dict)

def unload():
  """ Unloads the module by calling any unload/unbind functions."""
  modutils.unload_commands(commands_dict.keys())