/****************************************************************************
**
** $Id: ltemplate.cpp,v 1.3 2002/04/13 13:23:47 hausmann Exp $
**
** Copyright (C) 1999 Calderasystems, Inc
** All rights reserved.
**
** This file is part of the Caldera OpenLinux Installer.
** Original Implementation: 1999 by Troll Tech AS
**
** This file may be distributed under the terms of the Q Public License
** as defined by Troll Tech AS of Norway and appearing in the file
** LICENSE included in the packaging of this file.
**
*****************************************************************************/


#include <qdict.h>
#include <qtextstream.h>
#include <qregexp.h>

#include "ltemplate.h"


LTemplate::LTemplate(QString temp)
  : tpl(temp), tokens(17,FALSE)
{
}


void LTemplate::addToken(const char *token, const char *value)
{
  if (value)
    tokens.insert(token,strdup(value));
  else
    tokens.insert(token,"");
}


void LTemplate::write(QString target)
{
  // try to open the template
  if (tpl.open(IO_ReadOnly))
    {
      QTextStream input(&tpl);
      
      // try to open the output
      QFile outfile(target);
      if (outfile.open(IO_WriteOnly))
	{
	  QTextStream output(&outfile);

	  // copy the file
	  while (!input.eof())
	    {
	      QString line = input.readLine();
	      output << substitute(line) << endl;
	    }

	  outfile.close();
	}
	  
      tpl.close();
    }
}


QString LTemplate::substitute(QString line)
{
 QDictIterator<char> it(tokens);
  while (it.current())
    {
      QString exp("\\$\\{%1\\}");
      exp = exp.arg(it.currentKey());
      QRegExp regexp(exp,FALSE);
      line = line.replace(regexp, it.current());
      ++it;
    }

  return line;
}

