# -*-perl-*-

#+##############################################################################
#
# chm.init: convert to chm intermediate formats hhp, hhc, hhk and html files
#
#    Copyright (C) 2004-2008  Patrice Dumas <pertusus@free.fr>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
#    02110-1301  USA
#
#-##############################################################################

use strict;

#html_default_load();
t2h_default_load_format('html');

$TOP_NODE_FILE = undef;
$TOP_FILE = undef;

#$SECTION_NAVIGATION = 0; # to avoid headers in normal elements
$SHOW_MENU = 0;
$SPLIT = 'node';
set_conf('contents', 1);
$SPLIT_INDEX = undef;
$IDX_SUMMARY = 1;

$SMALL_RULE = '';
$DEFAULT_RULE = '';
$MIDDLE_RULE = '';
$BIG_RULE = '';

$DOCUMENT_DESCRIPTION = '';
$FOOTNOTESTYLE = 'end';

#FIXME remove that later
$USE_SECTIONS = 1;

push @command_handler_process, \&chm_initialize_variables;

$index_summary_file_entry = \&chm_index_summary_file_entry;
$index_summary_file_begin = \&chm_index_summary_file_begin;
$index_summary_file_end = \&chm_index_summary_file_end;

$print_page_foot = \&chm_print_page_foot;
# no-ops to avoid headers and footers
$print_head_navigation = \&chm_noop;
#$print_Top_footer = \&chm_noop;
$print_foot_navigation = \&chm_noop;

my $default_toc_body = $toc_body;
$toc_body = \&chm_toc_body;

$finish_out = \&chm_finish_out;
my $default_init_out = $init_out;

$init_out = \&chm_init_out;

my %chm_languages = (
    'en'         => '0x409 English (United States)',
    'sq'         => '0x041c Albanian',
#    'ar'         => '0x1401 Arabic (ALGERIA)',
#    'es'         => '0x2c0a Spanish (ARGENTINA)',
#    'en'         => '0x0c09 English (AUSTRALIA)',
#    'de'         => '0x0c07 German (AUSTRIA)',
#    'ar'         => '0x3c01 Arabic (BAHRAIN)',
    'be'         => '0x0423 Byelorussian',
#    'fr'         => '0x080c French (BELGIUM)',
#    'en'         => '0x2809 English (BELIZE)',
#    'es'         => '0x400a Spanish (BOLIVIA)',
#    'pt'         => '0x0416 Portuguese (BRAZIL)',
#    'ms'         => '0x083e Malay (BRUNEI DARUSSALAM)',
    'bg'         => '0x0402 Bulgarian',
#    'fr'         => '0x0c0c French (CANADA)',
#    'es'         => '0x340a Spanish (CHILE)',
    'zh'         => '0x0804 Chinese (CHINA)',
#    'es'         => '0x240a Spanish (COLOMBIA)',
#    'es'         => '0x140a Spanish (COSTA RICA)',
    'hr'         => '0x041a Croatian',
    'cs'         => '0x0405 Czech',
    'da'         => '0x0406 Danish',
#    'es'         => '0x1c0a Spanish (DOMINICAN REPUBLIC)',
#    'es'         => '0x300a Spanish (ECUADOR)',
#    'ar'         => '0x0c01 Arabic (EGYPT)',
#    'es'         => '0x440a Spanish (EL SALVADOR)',
    'et'         => '0x0425 Estonian',
    'fo'         => '0x0438 Faeroese',
    'fi'         => '0x040b Finnish',
    'fr'         => '0x040c French (FRANCE)',
    'de'         => '0x0407 German (GERMANY)',
    'el'         => '0x0408 Greek',
#    'es'         => '0x100a Spanish (GUATEMALA)',
#    'es'         => '0x480a Spanish (HONDURAS)',
#    'zh'         => '0x0c04 Chinese (HONG KONG)',
    'hu'         => '0x040e Hungarian',
    'is'         => '0x040f Icelandic',
    'hi'         => '0x0439 Hindi',
    'in'         => '0x04',
    'fa'         => '0x0429 Farsi',
#    'ar'         => '0x0801 Arabic (IRAQ)',
#    'en'         => '0x1809 English (IRELAND)',
    'iw'         => '0x04',
    'it'         => '0x0410 Italian',
#    'en'         => '0x2009 English (JAMAICA)',
    'ja'         => '0x0411 Japanese',
#    'ar'         => '0x2c01 Arabic (JORDAN)',
    'sw'         => '0x0441 Swahili',
    'ko'         => '0x0412 Korean',
#    'ar'         => '0x3401 Arabic (KUWAIT)',
    'al'         => '0x0426 Latvian (Lettish)',
#    'ar'         => '0x3001 Arabic (LEBANON)',
#    'ar'         => '0x1001 Arabic (LIBYAN ARAB JAMAHIRIYA)',
#    'de'         => '0x1407 German (LIECHTENSTEIN)',
    'lt'         => '0x0427 Lithuanian',
#    'de'         => '0x1007 German (LUXEMBOURG)',
#    'zh'         => '0x1404 Chinese (MACAU)',
    'mk'         => '0x042f Macedonian',
#    'ms'         => '0x043e Malay (MALAYSIA)',
#    'es'         => '0x080a Spanish (MEXICO)',
#    'fr'         => '0x180c French (MONACO)',
#    'ar'         => '0x1801 Arabic (MOROCCO)',
    'nl'         => '0x0413 Dutch',
#    'en'         => '0x1409 English (NEW ZEALAND)',
#    'es'         => '0x4c0a Spanish (NICARAGUA)',
    'no'         => '0x0414 Norwegian',
#    'ar'         => '0x2001 Arabic (OMAN)',
    'ur'         => '0x0420 Urdu',
#    'es'         => '0x180a Spanish (PANAMA)',
#    'es'         => '0x3c0a Spanish (PARAGUAY)',
#    'es'         => '0x280a Spanish (PERU)',
#    'en'         => '0x3409 English (PHILIPPINES)',
    'pl'         => '0x0415 Polish',
    'pt'         => '0x0816 Portuguese (PORTUGAL)',
#    'es'         => '0x500a Spanish (PUERTO RICO)',
#    'ar'         => '0x4001 Arabic (QATAR)',
    'ro'         => '0x0418 Romanian',
    'ru'         => '0x0419 Russian',
    'ar'         => '0x0401 Arabic (SAUDI ARABIA)',
#    'zh'         => '0x1004 Chinese (SINGAPORE)',
    'sk'         => '0x041b Slovak',
    'sl'         => '0x0424 Slovenian',
    'af'         => '0x0436 Afrikaans',
    'ca'         => '0x0403 Catalan',
    'sv'         => '0x041d Swedish',
#    'de'         => '0x0807 German (SWITZERLAND)',
#    'ar'         => '0x2801 Arabic (SYRIAN ARAB REPUBLIC)',
#    'zh'         => '0x0404 Chinese (TAIWAN, PROVINCE OF CHINA)',
    'th'         => '0x041e Thai',
#    'en'         => '0x2c09 English (TRINIDAD AND TOBAGO)',
#    'ar'         => '0x1c01 Arabic (TUNISIA)',
    'tr'         => '0x041f Turkish',
    'uk'         => '0x0422 Ukrainian',
#    'ar'         => '0x3801 Arabic (UNITED ARAB EMIRATES)',
#    'en'         => '0x0809 English (UNITED KINGDOM)',
#    'en'         => '0x0409 English (UNITED STATES)',
#    'es'         => '0x380a Spanish (URUGUAY)',
#    'es'         => '0x200a Spanish (VENEZUELA)',
    'vi'         => '0x242a Vietnamese',
#    'ar'         => '0x2401 Arabic (YEMEN)',
#    'en'         => '0x3009 English (ZIMBABWE)',
    #''         => '',
);

my %hhk_global_property = (
   'ImageType' => 'Folder',
);

my %hhc_global_property = (
   'ImageType' => 'Folder',
);


######################################### not used
#
# if needed texi to unicode, maybe this could be in utf8.init, but currently
# no unicode
my %chm_texi_map = %texi_map;
my %chm_simple_map_texi = %simple_map_texi;
my %chm_style_map_texi = ();

foreach my $command (keys(%style_map_texi))
{
    $chm_style_map_texi{$command} = {}; 
    foreach my $key (keys (%{$style_map_texi{$command}}))
    {
#print STDERR "$command, $key, $style_map_texi{$command}->{$key}\n";
         $chm_style_map_texi{$command}->{$key} = 
              $style_map_texi{$command}->{$key};
    }
}

foreach my $key (keys(%unicode_accents))
{
#    $chm_style_map{$key}->{'function'} = \&t2h_utf8_accent;
    $chm_style_map_texi{$key}->{'function'} = \&t2h_utf8_accent;
}

foreach my $key (%things_map)
{
    if (exists($unicode_map{$key}) and ($unicode_map{$key} ne ''))
    {
#        $chm_things_map{$key} = chr(hex($unicode_map{$key}));
        $chm_texi_map{$key} = chr(hex($unicode_map{$key}));
    }
}

$chm_simple_map_texi{"\n"} = ' ';
######################################### end not used

# at least kchmviewer has trouble with the corresponding textual entities
foreach my $thing ('OE', 'oe', 'euro')
{
     $things_map{$thing} = $numeric_entity_map{$thing};
     $pre_map{$thing} = $numeric_entity_map{$thing};
     $simple_format_texi_map{$thing} = $numeric_entity_map{$thing};
}

my $hhp_lines;
# this cannot be in chm_init_out, because it should be before toc_body
# call.
sub chm_initialize_variables()
{
    $hhp_lines = '';
}

sub chm_init_out()
{
    &$default_init_out();
# Setting out file encoding to utf8 doesn't work. Seen on the web that 
# htmlhelp 1.x isn't utf8 aware
#   $Texi2HTML::THISDOC{'OUT_ENCODING'} = 'utf8';
    return if ($null_device_file{$Texi2HTML::THISDOC{'filename'}->{'top'}});
    my $hhk_file = "$Texi2HTML::THISDOC{'destination_directory'}$Texi2HTML::THISDOC{'file_base_name'}" . ".hhk";
    open (IDXFILE, ">$hhk_file") or
        die "Can't open $hhk_file for writing: $!\n";
    if ($USE_UNICODE and defined($Texi2HTML::THISDOC{'OUT_ENCODING'}) and $Texi2HTML::THISDOC{'OUT_ENCODING'} ne '')
    {
        binmode(IDXFILE, ":encoding($Texi2HTML::THISDOC{'OUT_ENCODING'})");
    }
    
    print "# writing HTML Help index in $hhk_file...\n" if $VERBOSE;
    print IDXFILE "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML//EN\">\n<HTML>\n";
    print IDXFILE "<HEAD>\n<meta name=\"GENERATOR\" content=\"$Texi2HTML::THISDOC{program}\">\n";
    print IDXFILE "<!-- Sitemap 1.0 -->\n</HEAD>\n<BODY>\n";
    print IDXFILE "<OBJECT type=\"text/site properties\">\n";
    foreach my $property (sort(keys(%hhk_global_property)))
    {
        print IDXFILE "<param name=\"$property\" value=\"$hhk_global_property{$property}\">\n";
       
    }
    print IDXFILE "</OBJECT>\n";

    my $hhp_file = "$Texi2HTML::THISDOC{'destination_directory'}$Texi2HTML::THISDOC{'file_base_name'}.hhp";
    print "# writing HTML Help project in $hhp_file...\n" if $VERBOSE;
    open (HHPFILE, ">$hhp_file") or
        die "Can't open $hhp_file for writing: $!\n";
    if ($USE_UNICODE and defined($Texi2HTML::THISDOC{'OUT_ENCODING'}) and $Texi2HTML::THISDOC{'OUT_ENCODING'} ne '')
    {
        binmode(HHPFILE, ":encoding($Texi2HTML::THISDOC{'OUT_ENCODING'})");
    }
    my $language = $chm_languages{'en'};
    my $documentlanguage = get_conf('documentlanguage');
    $documentlanguage =~ s/_.*//;
    if (exists ($chm_languages{$documentlanguage}))
    {
        $language = $chm_languages{$documentlanguage};
    }
    my $title = main::remove_texi($Texi2HTML::THISDOC{'title_texi'});
    my $top_file = $Texi2HTML::THISDOC{'filename'}->{'top'};
    print HHPFILE <<EOT;
[OPTIONS]
Compatibility=1.1 or later
Compiled file=$Texi2HTML::THISDOC{'file_base_name'}.chm
Contents file=$Texi2HTML::THISDOC{'file_base_name'}.hhc
Default Window=Default
Default topic=$top_file
Display compile progress=No
Full-text search=Yes
Index file=$Texi2HTML::THISDOC{'file_base_name'}.hhk
Language=$language
Title=$title

[WINDOWS]
Default=,"$Texi2HTML::THISDOC{'file_base_name'}.hhc","$Texi2HTML::THISDOC{'file_base_name'}.hhk","$top_file","$top_file",,,,,0x22520,,0x384e,,,,,,,,0

[FILES]
EOT
}

sub chm_print_page_foot($)
{
    my $fh = shift;
    print $fh <<EOT;
<p>
$PRE_BODY_CLOSE
</p>
</body>
</html>
EOT
}

sub chm_noop($$)
{
    return '';
}

# Convert texi to string
sub chm_text($)
{
    my $text = shift;
    return main::simple_format(undef,undef,'chm_text',$text);
}

my @hhc_elements;

# For hhc, collect elements here, do the formatting later
sub chm_toc_body($)
{
    my $elements_ref = shift;
    &$default_toc_body($elements_ref);
    my %chm_files;
    @hhc_elements = @$elements_ref;

    foreach my $element (@$elements_ref)
    {
        if (!$chm_files{$element->{'file'}})
        {
             $hhp_lines .= "$element->{'file'}\n";
             $chm_files{$element->{'file'}} = 1;
        }
    }
}

# key:          
# origin_href:  
# entry:        
# texi entry: 
# element_href: 
# element_text: 
sub chm_index_summary_file_entry ($$$$$$$$)
{
    my $name = shift;
    my $key = shift;
    my $origin_href = shift;
    my $entry = shift;
    my $text = '';
    #$entry = &$protect_text($key);
    my $texi_entry = shift;
    my $element_href = shift;
    my $element_text = shift;
    my $is_printed = shift;
    $entry = chm_text($texi_entry);
    print IDXFILE "<LI> <OBJECT type=\"text/sitemap\">\n<param name=\"Name\" value=\"$entry\">\n<param name=\"Local\" value=\"$origin_href\">\n</OBJECT> </LI>\n" if ($key =~ /\S/);
}

sub chm_index_summary_file_begin($$)
{
    my $name = shift;
    my $is_printed = shift;
    # avoid entities in hh* files.
    t2h_default_set_iso_symbols(0);
}

# file is not closed here but in finish_out.
sub chm_index_summary_file_end($$)
{
    my $name = shift;
    my $is_printed = shift;
}

sub chm_finish_out()
{
    return if ($null_device_file{$Texi2HTML::THISDOC{'filename'}->{'top'}});
    print IDXFILE "</BODY>\n</HTML>\n";
    close (IDXFILE);
    my $hhc_file = "$Texi2HTML::THISDOC{'destination_directory'}$Texi2HTML::THISDOC{'file_base_name'}.hhc";
    open (HHCFILE, ">$hhc_file") or
        die "Can't open $hhc_file for writing: $!\n";
    if ($USE_UNICODE and defined($Texi2HTML::THISDOC{'OUT_ENCODING'}) and $Texi2HTML::THISDOC{'OUT_ENCODING'} ne '')
    {
        binmode(HHCFILE, ":encoding($Texi2HTML::THISDOC{'OUT_ENCODING'})");
    }
    
    print HHCFILE "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML//EN\">\n<HTML>\n";
    print HHCFILE "<HEAD>\n<meta name=\"GENERATOR\" content=\"$Texi2HTML::THISDOC{program}\">\n";
    print HHCFILE "<!-- Sitemap 1.0 -->\n</HEAD>\n<BODY>\n";
    print HHCFILE "<OBJECT type=\"text/site properties\">\n";
    foreach my $property (sort(keys(%hhc_global_property)))
    {
        print HHCFILE "<param name=\"$property\" value=\"$hhc_global_property{$property}\">\n";
       
    }
    print HHCFILE "</OBJECT>\n";
    my @hhc_lines = ();
    my $level = 0;
    foreach my $element (@hhc_elements)
    {
        while ($level != $element->{'toc_level'})
        {
            if ($level < $element->{'toc_level'})
            {
                 push (@hhc_lines, "<UL>\n");
                 $level++;
            }
            elsif ($level > $element->{'toc_level'})
            {
                 push (@hhc_lines, "</UL>\n");
                 $level--;
            }
        }
        my $text = '';
        if ($NUMBER_SECTIONS and defined($element->{'number'}) and $element->{'number'} ne '')
        {
             $text .= $element->{'number'} . " ";
             
        }
        $text .= chm_text($element->{'texi'});
        push (@hhc_lines, "<LI> <OBJECT type=\"text/sitemap\">\n<param name=\"Name\" value=\"$text\">\n<param name=\"Local\" value=\"$element->{'file'}#$element->{'target'}\">\n</OBJECT> </LI>\n");
    }
    while ($level > 0)
    {
         push (@hhc_lines, "</UL>\n");
         $level--;
    }
    main::print_lines(\*HHCFILE, \@hhc_lines);
    print HHCFILE "</HTML>\n</BODY>\n";
    print HHPFILE $hhp_lines;
    close (HHPFILE);
}

1;
