require 'dhelp/exporter/base'
require 'dhelp/exporter/cgimap'
require 'erb'
require 'fileutils'
require 'gettext'

module Dhelp::Exporter

  FORMAT_NAMES = {:html             => 'HTML',
                  :pdf              => 'PDF',
                  :postscript       => 'PostScript',
                  :"debiandoc-sgml" => 'DebianDoc-SGML',
                  :dvi              => 'DVI'}

  class Html < Base

    attr_reader :section_template, :index_template
    attr_writer :section_template, :index_template

    def initialize(doc_pool, options={})
      super(doc_pool, options)
      @section_template = template_dir + "/section.rhtml"
      @index_template = template_dir + "/index.rhtml"
    end

    def recreate_export_dir(create_mode)
      FileUtils.rm_rf(export_dir)
      FileUtils.mkdir_p(export_dir, :mode => create_mode)
      FileUtils.chdir(export_dir)
      # Create README file
      File.open("README", "w") do |f|
        f.puts <<EOREADME
Don't put files in this directory!
dhelp will delete *all* files in this directory when creating a new index.

Esteban Manchado Velázquez (zoso@debian.org)
EOREADME
      end
    end

    def make_page(template, page_dir, page_filename)
      page_path = File.join(page_dir, page_filename)

      tmpl = ERB.new(File.read(template))
      html = tmpl.result(binding)

      FileUtils.mkdir_p(page_dir, :mode => 0755)
      File.open(page_path, "w") do |f|
        f.print html
      end
      File.chmod 0644, page_path
    end

    def export()
      recreate_export_dir(0755)

      # Variables for the template
      @section_tree = doc_pool.section_tree

      # Generate section pages from the tree

      @section_tree.each_pair do |section, contents|
        # section first
        export_section_page(section, contents[:documents])
        # then subsections
        contents[:subsections].each_pair do |subsection, subcontents|
          export_section_page(File.join(section,subsection), subcontents[:documents])
        end
      end

      # Write special "section page" for all the docs

      all_docs = []
      @section_tree.each_pair do |section, contents|
        all_docs += contents[:documents]
        all_docs += contents[:subsections].map {|ss, ssc| ssc[:documents]}.flatten
      end
      export_section_page("All", all_docs)

      # Create general index file, now that the sections are already there

      make_page(index_template, export_dir, "index.html")

    rescue Errno::EACCES # => e
      $stderr.puts "Don't have permissions to regenerate the HTML help"
      exit 1
    end

    def export_section_page(section, itemlist)

      # Variables for the template
      @section_title = Dhelp.capitalize_section(section)
      @supported_formats = Dhelp::SUPPORTED_FORMATS
      @item_list         = itemlist.sort{ |a,b|
        a.title.downcase <=> b.title.downcase
      }
      @doc_path_prefix   = "../" * (section.split('/').size + 1) # count "HTML/"
        
      # Create section index file
      make_page(section_template, section_dir, "index.html")
    end

    # Returns the correct name for each format
    def format_name(format)
      Dhelp::Exporter::FORMAT_NAMES[format.downcase.to_sym] || format.capitalize
    end

    # Returns a suitable URL for the given path
    def resource_url(path)
      path.sub(/\/usr\/share\/doc\//, @doc_path_prefix)
    end

    def section_dir()
      return File.join(@export_dir, @section_title)
    end

  end   # class Html
end   # module Dhelp::Exporter
