# Generator.pm
#
# SuperClass for all generators
# Open files, writes into and close them
#
# Ralf Peine, 2004-05-26 Tue

use strict;

package Efg::Generator;

use Log;
use CFG;

use Efg::Base;

use vars qw (%ConfigKeyNames @ISA);

@ISA = qw(Efg::Base);

$ConfigKeyNames{OUTPUT_DIR} = '_output_dir';

sub init {
    my $self = shift;

    $self->{_file} = '';           # Output File
    $self->{_commentChar} = '#';   # Comment Char
    $self->{_parser} = undef;
    $self->{_noBreak} = 'true';    # no exit for errors

    my $outDir = $CFG{"OUTPUT_DIR"};
    $outDir =~ s/\\/\//gio;
    $self->{_output_dir} = $outDir;
}

sub setParser {
    my $self   = shift;
    my $parser = shift;

    $self->{_parser} = $parser;
}


sub getConfigKeyNamesRef {
    return \%ConfigKeyNames;
}

sub outputFile { # add and open output file
    my $self = shift;

    my $file = shift;

    $file = "$self->{_output_dir}/$file";

    $self->{_fh}->close() if $self->{_fh}; 

    $self->{_file} = $file;
    $self->{_fh} = new FileHandle (">$file");
    unless (defined $self->{_fh}) {
	$self->errorMsg(0002, "$file:$.", "Can't open file $file for writing: $!\n");
	exit 1;
    }

    $self->write("# generated by $0 (version $Efg::version) at ".localtime()."\n");

    return 1;
}

sub writeComment {
    my $self = shift;
    $self->{_fh}->write($self->{_commentChar}. join ('',@_));
}

sub parseForAndInsertVariables {
    my $self = shift;

    my @resArr = $self->SUPER::parseForAndInsertVariables(@_);
    if ($self->{_error}) {

	my @caller = caller(1);
	my $func_name    = $caller[3];
	my $line_nbr     = $caller[2];
	my $file_name    = $caller[1];

	$self->errorMsg(0, "$file_name:$line_nbr", "Syntax error in $func_name() ".$self->{_error});
	exit 1 unless $self->{_noBreak};
    }
    return @resArr;
}

sub write {
    my $self = shift;
    $self->{_fh}->write(join('', @_));
}

1;
