/*
 *  Copyright 2006-2008 Mikhail Kryshen
 *
 *  This file is part of Tema.
 *
 *  Tema is free software: you can redistribute it and/or modify it
 *  under the terms of the GNU Lesser General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  Tema is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the 
 *  GNU Lesser General Public License along with Tema.  
 *  If not, see <http://www.gnu.org/licenses/>.
 *
 *  $Id: TemplateReader.java,v 1.8 2008/02/19 00:20:48 mikhail Exp $
 */

package kryshen.tema.io;

import java.io.Reader;
import java.io.LineNumberReader;
import java.io.PushbackReader;
import kryshen.tema.TemplateParser;

/**
 * Reader for Tema templates. Stores data source name (commonly
 * filename) and tracks line numbers for error reporting.
 *
 * @author Mikhail Kryshen
 */
public class TemplateReader extends PushbackReader {
    static final int UNREAD_BUFFER_SIZE;
    
    /* Calculate UNREAD_BUFFER_SIZE value. */
    static {
        int max = 0;
        
        for (String s : TemplateParser.BRACKET_OPEN) {
            max = Math.max(max, s.length());
        }
        
        for (String s : TemplateParser.BRACKET_CLOSE) {
            max = Math.max(max, s.length());
        }
        
        max = Math.max(max, TemplateParser.ESCAPE_NEWLINE.length() + 2);
        max = Math.max(max, TemplateParser.ESCAPE_WHITESPACE.length());
        
        UNREAD_BUFFER_SIZE = max;
    }
    
    private final String source;
    private final LineNumberReader lnReader;
    private final TemplateReader parentReader;
    
    public TemplateReader(Reader in) {
        this(new LineNumberReader(in));
    }
    
    public TemplateReader(Reader in, String source) {
        this(new LineNumberReader(in), source);
    }
    
    public TemplateReader(LineNumberReader in) {
        this(in, "");
    }
    
    public TemplateReader(LineNumberReader in, String source) {
        super(in, UNREAD_BUFFER_SIZE);
        
        this.parentReader = null;
        this.lnReader = in;
        this.source = source;
    }
    
    public TemplateReader(Reader in, TemplateReader parent) {
        super(in, UNREAD_BUFFER_SIZE);
        
        this.parentReader = parent;
        this.lnReader = null;
        this.source = null;
    }
    
    public String getSource() {
        if (source != null)
            return source;
        
        return parentReader.getSource();
    }
    
    public int getLineNumber() {
        if (lnReader != null)
            return lnReader.getLineNumber();
        
        return parentReader.getLineNumber();
    }
}