/*
 * Copyright (C) 2006 Mikhail A. Kryshen
 *
 * $Id: Define.java,v 1.1.1.1 2006/05/16 14:04:09 mikhail Exp $
 */

package kryshen.tema.functions;

import java.io.*;
import java.util.*;

import kryshen.tema.*;

public class Define extends Function {
    public Define() {
        super("define");
    }

    public int invoke(FunctionDataParser fdp, Writer out)
        throws IOException, TemplateException {
        
        final String arg0 = fdp.getNextArg();
        final String data = fdp.getData();

        Function newFunction = new Function(arg0) {
                public int invoke(final FunctionDataParser fdp, final Writer out)
                    throws IOException, TemplateException {

                    TemplateParser functionParser = 
                        new TemplateParser(fdp.getTemplateParser());
                    
                    functionParser.registerFunction(new Function("nextarg") {
                            public int invoke(FunctionDataParser unusedFdp, 
                                              final Writer out)
                                throws IOException, TemplateException {

                                return fdp.parseNextArg(out);
                            }
                        });

                    functionParser.registerFunction(new Function("data") {
                            public int invoke(FunctionDataParser unusedFdp, 
                                              final Writer out)
                                throws IOException, TemplateException {

                                return fdp.parseData(out);
                            }
                        });

                    return functionParser.parse(new StringReader(data), out);                                       
                }
            };

        fdp.getTemplateParser().registerFunction(newFunction);

        out.write(arg0);
        return 1;
    }
}