#!/usr/bin/perl -w 
#
# Zymonic Business Process and Information Management System
# Copyright Zednax Limited 2008 -
# For Authors and Changelog see the subversion history

use strict;

package main;

use Zymonic::Config;
use Zymonic;
use XML::Simple;
$Zymonic::system  = '';
$Zymonic::session = '';

BEGIN
{
    use Zymonic::Utils qw(death_handler debug);
    $main::SIG{__DIE__} = \&death_handler;
}

my $debug_file = '/var/log/zymonic_labels/import_' . time . '.log';
open my $fh, ">$debug_file" or die "Unable to open label import log: $debug_file";
$Zymonic::Utils::debugfile = $fh;
my $debug_prefix = 'ZZLI:';

my @errors = ();

$Zymonic::system = shift @ARGV;
my $file      = shift @ARGV;
my $lang_code = shift @ARGV;
my $subset    = join( ' ', @ARGV );

push( @errors, "No system specified" )        unless $Zymonic::system;
push( @errors, "No file specified" )          unless $file;
push( @errors, "No language code specified" ) unless $lang_code;
push( @errors, "No subset specified" )        unless $subset;

if ( scalar(@errors) > 0 )
{
    debug( "$debug_prefix: Errors - " . join( '; ', @errors ) );
    print join( "\n", @errors );
    print "\n\nUsage: zymonic_lang_importer.pl [system] [html file] [lang code] [subset]\n";
    exit(0);
}

debug("$debug_prefix: Starting label import for $lang_code, $subset: $file");

$Zymonic::ZCONFIG{$Zymonic::system} = Zymonic::Config->new(
    system_name => $Zymonic::system,
    config_dir  => "/etc/zymonic",
    ip_address  => 'LANGIMPORTER',
    protocol    => 'https'
);

my $html_in = XMLin($file);

die "HTML File should contain a body filled with <p> tags that have ids."
  unless ref($html_in)
      and ref( $html_in->{body} )
      and ref( $html_in->{body}->{p} )
      and ref( $html_in->{body}->{p} ) eq 'HASH';

$Zymonic::ZCONFIG{$Zymonic::system}->sys_opt( 'importing_zz_labels', 'Y' );
foreach my $label_digest ( keys( %{ $html_in->{body}->{p} } ) )
{

    # Add a new entry
    debug("$debug_prefix: Adding Label");
    $Zymonic::ZCONFIG{$Zymonic::system}->{DB}->run_statement(
        {
            string => "DELETE FROM zz_labels WHERE lang_code = ? AND subset = ? AND digest = ?",
            params => [ $lang_code, $subset, $label_digest ],
        }
    );
    $Zymonic::ZCONFIG{$Zymonic::system}->{DB}->ll_table()->insert(
        {
            key_content => { value => '' },
            content     => { value => $html_in->{body}->{p}->{$label_digest}->{content} },
            lang_code   => { value => $lang_code },
            subset      => { value => $subset },
            digest      => { value => $label_digest },
        }
    );
}
$Zymonic::ZCONFIG{$Zymonic::system}->sys_opt( 'importing_zz_labels', 'N' );
debug("Done importing labels");
