package WebPAC::Normalize::XML;

use warnings;
use strict;

use base qw/WebPAC::Common WebPAC::Normalize/;
use XML::Simple;
use Data::Dumper;
use Text::Iconv;

=head1 NAME

WebPAC::Normalize::XML - apply XML normalisaton rules

=head1 VERSION

Version 0.02

=cut

our $VERSION = '0.02';

=head1 SYNOPSIS

This module uses C<conf/normalize/*.xml> files to perform normalisation
from input records

=cut

=head1 FUNCTIONS

=head2 open

Read normalisation rules defined using XML from C<conf/normalize/*.xml> and
parse it.

 my $n = new WebPAC::Normalize::XML;
 $n->open(
 	tag => 'isis',
 	xml_file => '/path/to/conf/normalize/isis.xml',
 );

C<tag> defines tag to use within C<xml_file>

C<xml_file> defines path to normalize XML.

C<tags> define additional tags that can be forced (and an be array).

=cut

sub open {
	my $self = shift;

	my $arg = {@_};

	my $log = $self->_get_logger();

	foreach my $req (qw/tag xml_file/) {
		$log->logconfess("need argument $req") unless $arg->{$req};
	}

	$self->{'tag'} = $arg->{'tag'};
	my $xml_file = $arg->{'xml_file'};

	$log->info("using $xml_file tag <",$self->{'tag'},">");

	$log->logdie("normalisation xml file '$xml_file' doesn't exist!") if (! -e $xml_file);

	$self->{'import_xml_file'} = $xml_file;

	my @force_array = [ $self->{'tag'}, 'config', 'format' ];
	push @force_array, $self->{'tags'} if ($self->{'tags'});

	$self->{'import_xml'} = XMLin($xml_file,
		ForceArray => @force_array,
		ForceContent => 1,
	);

	$log->debug("import xml is ",sub { Dumper($self->{'import_xml'}) }, $self->{lookup} ? " using lookups" : "lookups disabled");

	return $self;
}


=head2 _x

Convert string from XML UTF-8 encoding to code page defined in C<xml_file>.

 my $text = $n->_x('utf8 text');

Default application code page is C<ISO-8859-2>. You will probably want to
change that when creating new instance of object based on this one.

=cut

sub _x {
	my $self = shift;
	my $utf8 = shift || return;

	# create UTF-8 convertor for import_xml files
	$self->{'utf2cp'} ||= Text::Iconv->new('UTF-8' ,$self->{'code_page'} || 'ISO-8859-2');

	return $self->{'utf2cp'}->convert($utf8) ||
		$self->_get_logger()->logwarn("can't convert '$utf8'");
}


=head1 AUTHOR

Dobrica Pavlinusic, C<< <dpavlin@rot13.org> >>

=head1 COPYRIGHT & LICENSE

Copyright 2005 Dobrica Pavlinusic, All Rights Reserved.

This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

=cut

1; # End of WebPAC::Normalize::XML
