package SIP::Template;

# Version number
$VERSION = 0.01;

use strict;
use HTML::Template;

use Opals::Context;

################################################################################
sub new {
  my $class = shift;
  my (%param) = (@_);

  my $this = {};
  bless $this, $class;

  $this->set(%param);

  return $this;
}

############################################################
sub init {
  my $this = shift;

  foreach my $k (keys %{$this}) {
    delete $this->{$k};
  }
}

############################################################
sub set {
  my $this = shift;

  return unless (@_);

  my (%param) = (@_);

  $this->init();

  my $filename    = $param{'filename'};
  my $global_vars = $param{'global_vars'};
  my $rootDir     = Opals::Context->config('rootDir');

  $this->{'template'} = HTML::Template->new(
    filename          => "$filename",
    path              => "$rootDir/htdocs/sip",
    global_vars       => "$global_vars",
    die_on_bad_params => 0,
    cache             => 1,
    shared_cache      => 0,
    loop_context_vars => 1,
  );
}

############################################################
sub param {
  my $this = shift;

  return unless (scalar(@_) > 0);

  #open TTT, '>>/tmp/ctho-ttt';
  if (scalar(@_) == 1) {
    my ($param) = (@_);
    if (ref($param) eq 'HASH') {
      $this->{'template'}->param(%{$param});

      #      foreach my $k (sort keys %{$param}) {
      #        print TTT "ref. $k: $param->{$k}\n";
      #      }
    }
  }
  elsif (scalar(@_) % 2 == 0) {
    my (%param) = (@_);
    $this->{'template'}->param(%param);

    #    foreach my $k (sort keys %param) {
    #      print TTT "hash $k: $param{$k}\n";
    #    }
  }

  #print TTT "\n";
  #close TTT;
}

############################################################
sub write {
  my $this = shift;

  return unless (@_);

  my (%param) = (@_);
  my $cgi = $param{'cgi'};
  my $contentType = $param{'contentType'} || 'text/xml';

  # Output
  print $cgi->header(
    -type    => $contentType,
    -expires => 'now',
    -charset => 'utf-8',
    ),
    $this->{'template'}->output;
}

1;
