# $Id: EventGrid.pm,v 1.1 2005/01/06 15:58:28 jkremer Exp $
# Copyright 2004 Sun Microsystems, Inc., All Rights Reserved.
# Sun Proprietary/Confidential: For Internal Use Only
package Catalog::EventGrid;

use strict;
use Catalog::Entry;
use XML::LibXML;
use base 'Catalog::Entry';
use Data::Dumper;


sub new {
  my ($class, $type, $dir) = @_;

  my $this = { "type"   => $type,
               "entry"  => "eventGrid.xml",
					"dir"    => $dir,
					"mp"     => {}
				 };
  bless($this, "Catalog::EventGrid");
  return $this->loadEntry();
}

sub load {
  my ($this) = @_;
  $this->{grid} = {};
  $this->_loadFile($this->{file});
}


sub _readArgs {
  my ($this, $file, $args) = @_;
  my $doc;

  if (open(O, $file)) {
	 my @l = <O>; close(O);
	 $doc = "@l";
	 if ($args){
		foreach my $name ( keys %$args){
		  my $arg = $args->{$name};
		  $doc =~ s/$name/$arg/;
		}
	 }
  } else {
	 $this->setError("Error opening $file: $! \n");
  }
  return $doc;
}

sub _loadFile {
  my ($this, $file, $args) = @_;

  my $parser = XML::LibXML->new();
  my $dom;
  eval {
	 my $doc = $this->_readArgs($file, $args);
	 $dom  = $parser->parse_string($doc);
  };
  if ((!$dom)||($@)){
	 $this->setError("Error parsing XML document element. $@");
	 return;
  }
  my $grid = $dom->getDocumentElement();
  foreach my $incElem ($grid->findnodes("include")){
	 $this->_loadInclude($incElem);
  }
  foreach my $eventElement ($grid->findnodes("event")){
	 $this->_loadEvent($eventElement);
  }
}


sub _loadInclude {
  my ($this, $incElem) = @_;

  my $args = {};
  my $file = $incElem->getAttribute("file");
  my $path = $this->{dir}.$file;

  foreach my $argElem ($incElem->findnodes("arg")){
	 $args->{$argElem->getAttribute("name")} = $argElem->textContent();
  }
  if (-f $path){
	 $this->_loadFile($path, $args);
  }
  else {
	  $path = $this->getCommonDir() . $file;
	 if (-f $path){
		$this->_loadFile($path, $args);
	 }
	 else {
		$this->setError("Error including file $path.");
	 }
  }
}

sub _loadEvent {
  my ($this, $node) = @_;

  my $values = {};
  foreach my $el ($node->getChildNodes()){
	 if ($el->getType() == &XML::LibXML::ELEMENT_NODE() ){
		$values->{$el->getName()} = $el->textContent();
	 }
  }
  $this->{grid}->{ $values->{type} } = $values;
}


sub outProperties {
  my ($this) = @_;
  my $out;

  my $grid = $this->{grid};
  my $type = $this->{type};

  $out .= "# $type.grid\n";
  $out .= "# Autogenerated from " . $this->{dir} . "/eventGrid.xml\n\n";

  foreach my $type (keys %$grid){
	 my $event = $grid->{type};

	 foreach my $name (sort keys %$event){
		my $var = $event->{name};
		# sr \n -> \n'
		$out .= $name . "=" . $var . "\n";
	 }
	 $out .= "\n\n";
  }

  return $out;
}

# TODO: 1. add codes, 2. write to System/EGrid, 3 fix search/replace

1;
