require 'fileutils'

require 'rdoc/generator'
require 'rdoc/generator/html'
require 'rdoc/markup/to_html'

##
# We're responsible for generating all the HTML files from the object tree
# defined in code_objects.rb. We generate:
#
# [files]   an html file for each input file given. These
#           input files appear as objects of class
#           TopLevel
#
# [classes] an html file for each class or module encountered.
#           These classes are not grouped by file: if a file
#           contains four classes, we'll generate an html
#           file for the file itself, and four html files
#           for the individual classes.
#
# [indices] we generate three indices for files, classes,
#           and methods. These are displayed in a browser
#           like window with three index panes across the
#           top and the selected description below
#
# Method descriptions appear in whatever entity (file, class, or module) that
# contains them.
#
# We generate files in a structure below a specified subdirectory, normally
# +doc+.
#
#  opdir
#     |
#     |___ files
#     |       |__  per file summaries
#     |
#     |___ classes
#             |__ per class/module descriptions
#
# HTML is generated using the Template class.

class RDoc::Generator::XHTML < RDoc::Generator::HTML

  def gen_an_index(collection, title, template, filename)
    template = RDoc::TemplatePage.new @template::FR_INDEX_BODY, template
    res = []
    collection.sort.each do |f|
      if f.document_self
        res << { "href" => f.path, "name" => f.index_name }
      end
    end

    values = {
      "entries"    => res,
      'list_title' => CGI.escapeHTML(title),
      'index_url'  => main_url,
      'charset'    => @options.charset,
      'style_url'  => style_url('', @options.css),
      'mathml_xsl_url' => style_url('', "mathml.xsl"),
    }

    open filename, 'w' do |f|
      template.write_html_on(f, values)
    end
  end

  ##
  # Build the initial indices and output objects
  # based on an array of TopLevel objects containing
  # the extracted information.

  def generate(*args)
    super(*args)

    copy_xsls
  end

  def copy_xsls
    xsl_files = ["mathml.xsl", "pmathmlcss.xsl", "ctop.xsl", "pmathml.xsl"]
    xsl_dir = "rdoc/generator/xhtml"
    hit = 0
    $LOAD_PATH.each{ |path|
      hit = 0
      xsl_files.each{ |file|
        hit += 1 if ::File.exist?(::File.join(path, xsl_dir, file))
      }
      if hit >= 4
        xsl_files.each{ |file|
          ::FileUtils.copy(::File.join(path, xsl_dir, file), "./")
        }
        break
      else
        hit = 0
      end
    }
    if hit < 4
      $stderr.puts "Couldn't find xsl files (#{xsl_files.join(', ')})\n"
      exit
    end
  end

end

class RDoc::Generator::XHTMLInOne < RDoc::Generator::HTMLInOne

end
