/*
 *  Draco Econometrics
 *  Copyright (C) 2006-2009 Approximatrix, LLC
 *  http://www.approximatrix.com
 *  
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.approximatrix.draco.editor.syntax.comments;

public abstract class TokenPerLineCommentEngine extends AbstractCommentEngine {
	
	public String toggleComment(final String original) {
		if(original == null)
			return null;
		
		String[] lines = splitLines(original);
		
		// First to check if all lines start with a comment
		boolean allcomments = true;
		for(int i=0;i<lines.length && allcomments;i++) {
			if(lines[i].trim().length() > 0)
				allcomments = lines[i].trim().startsWith(getToken());
		}
		
		String ret = null;
		
		// Turn off comments
		if(allcomments) {
			ret = original.replaceAll("(?<=[\r\n|\r|\n][\t ]{0,"+Integer.toString(original.length())+"})"+getToken(), "");
			ret = ret.replaceFirst("(?<=^[\t ]{0,"+Integer.toString(ret.length())+"})"+getToken(), "");
		
		// Turn on comments
		} else {			
			ret = original.replaceAll("\r\n(?=[\t ]{0,"+Integer.toString(original.length())+"}[^\\s"+getToken()+"])", "\r\n"+getToken());
			ret = ret.replaceAll("\r(?=[\t ]{0,"+Integer.toString(ret.length())+"}[^\\s"+getToken()+"])", "\r"+getToken());
			ret = ret.replaceAll("\n(?=[\t ]{0,"+Integer.toString(ret.length())+"}[^\\s"+getToken()+"])", "\n"+getToken());
			
			if(lines[0].trim().length() > 0)
				ret = "#" + ret;
		}
		
		return ret;
	}
	
	protected abstract String getToken();
}
