/**
 * License Agreement.
 *
 * Rich Faces - Natural Ajax for Java Server Faces (JSF)
 *
 * Copyright (C) 2007 Exadel, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation.
 *
 * This library 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 this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 */

package org.richfaces.cdk.rd.generator;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;

import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugin.logging.SystemStreamLog;
import org.codehaus.plexus.util.IOUtil;

/**
 * @author Anton Belevich
 * 	
 */
public class ScriptAssembler implements ResourceAssembler {

	protected Log log = new SystemStreamLog();
	
	private StringBuilder builder = new StringBuilder();
	
	
	public void assembly(URL resource) {
		log.info("process resource : " + resource.getFile());
		
		try {
			builder.append(IOUtil.toString(resource.openStream()));
			builder.append("\n");
		} catch (IOException e) {
			log.error("Error read resource: " + resource.getFile());
		}
		
	}

	public void writeToFile(File file) {
		if(builder.length() > 0) {
		
			try {
				FileWriter fileWriter = new FileWriter(file);
			
				try {
					IOUtil.copy(builder.toString(), fileWriter);
				} finally {
					fileWriter.close();
				}
				
			} catch (IOException e) {
				log.error("Error write file: " + file.getAbsolutePath(),e);	
			}
			
		}	
	}
}
