package org.gradle.incap.impl.data.util;

import static javax.lang.model.SourceVersion.latestSupported;

import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import org.gradle.incap.Annotation1;
import org.gradle.incap.InputTypeFinder;
import org.gradle.incap.impl.data.InputType;

@SupportedAnnotationTypes("*")
public class InputTypeFinderAnnotationTestProcessor extends AbstractProcessor {

  private InputTypeFinder inputTypeFinder = new InputTypeFinder();
  private InputType inputTypeForElement;

  @Override
  public SourceVersion getSupportedSourceVersion() {
    return latestSupported();
  }

  @Override
  public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {

    if (roundEnv.processingOver()) {
      return false;
    }

    Set<? extends Element> elementsAnnotatedWith =
        roundEnv.getElementsAnnotatedWith(Annotation1.class);

    if (elementsAnnotatedWith.size() != 1) {
      throw new IllegalStateException(
          "There must be exactly one element to process. Actual=" + elementsAnnotatedWith.size());
    }

    for (Element element : elementsAnnotatedWith) {
      inputTypeForElement = inputTypeFinder.findInputTypeForElement(element);
    }

    return false;
  }

  public InputType getInputTypeForElement() {
    return inputTypeForElement;
  }
}