/*******************************************************************************
 * Copyright (c) 2006, 2008 BEA Systems, Inc. 
 *
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License 2.0
 * which accompanies this distribution, and is available at
 * https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contributors:
 *    jgarms@bea.com - initial API and implementation
 *    
 *******************************************************************************/
package org.eclipse.jdt.apt.tests.annotations.filegen;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

import org.eclipse.jdt.apt.tests.annotations.BaseProcessor;
import org.eclipse.jdt.apt.tests.annotations.ProcessorTestStatus;

import com.sun.mirror.apt.AnnotationProcessorEnvironment;
import com.sun.mirror.apt.Filer;
import com.sun.mirror.declaration.AnnotationTypeDeclaration;
import com.sun.mirror.declaration.Declaration;

public class TextGenAnnotationProcessor extends BaseProcessor {
	
	public TextGenAnnotationProcessor(AnnotationProcessorEnvironment env) {
		super(env);
	}
	
	public void process() {
		ProcessorTestStatus.setProcessorRan();
		Filer f = _env.getFiler();
		AnnotationTypeDeclaration annoDecl = (AnnotationTypeDeclaration) _env.getTypeDeclaration(TextGenAnnotation.class.getName());
		Collection<Declaration> annotatedDecls = _env.getDeclarationsAnnotatedWith(annoDecl);
		try {
			for (Declaration annotatedDecl : annotatedDecls) {
				TextGenAnnotation tganno = annotatedDecl.getAnnotation(TextGenAnnotation.class);
				String fileName = tganno.value();
				PrintWriter writer = f.createTextFile(
						Filer.Location.CLASS_TREE, 
						"", 
						new File(fileName), 
						null);
				writer.print(TEXT);
				writer.close();
			}
			reportSuccess(this.getClass());
		}
		catch (NullPointerException npe) {
			reportError(this.getClass(), "Could not read annotation in order to generate text file");
		}
		catch (IOException ioe) {
			reportError(this.getClass(), "Could not generate text file due to IOException");
		}
	}
	
	private static final String TEXT = "This is some text generated by an annotation processor";

}
