/*
   Copyright 2015 Immutables Authors and Contributors

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package org.immutables.metainf.processor;

import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.tools.Diagnostic;
import org.immutables.generator.AbstractTemplate;
import org.immutables.generator.AnnotationMirrors;
import org.immutables.generator.Generator;
import org.immutables.generator.TypeHierarchyCollector;
import org.immutables.metainf.Metainf;

@Generator.Template
class Metaservices extends AbstractTemplate {

  ListMultimap<String, String> allMetaservices() {
    ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();

    for (Element element : round().getElementsAnnotatedWith(Metainf.Service.class)) {
      @Nullable TypeElement typeElement = validated(element);
      if (typeElement == null) {
        continue;
      }
      Set<String> interfaceNames = extractServiceInterfaceNames(typeElement);
      builder.putAll(typeElement.getQualifiedName().toString(), interfaceNames);
    }

    return builder.build();
  }

  private Set<String> extractServiceInterfaceNames(TypeElement typeElement) {
    ImmutableList<TypeMirror> typesMirrors =
        AnnotationMirrors.getTypesFromMirrors(
            Metainf.Service.class.getCanonicalName(), "value", typeElement.getAnnotationMirrors());

    if (typesMirrors.isEmpty()) {
      return useIntrospectedInterfacesForServices(typeElement);
    }

    return useProvidedTypesForServices(typeElement, typesMirrors);
  }

  private Set<String> useIntrospectedInterfacesForServices(TypeElement typeElement) {
    TypeHierarchyCollector typeHierarchyCollector = new TypeHierarchyCollector();
    typeHierarchyCollector.collectFrom(typeElement.asType());
    return typeHierarchyCollector.implementedInterfaceNames();
  }

  private Set<String> useProvidedTypesForServices(TypeElement typeElement, ImmutableList<TypeMirror> typesMirrors) {
    List<String> wrongTypes = Lists.newArrayList();
    List<String> types = Lists.newArrayList();
    for (TypeMirror typeMirror : typesMirrors) {
      if (typeMirror.getKind() != TypeKind.DECLARED
          || !processing().getTypeUtils().isAssignable(typeElement.asType(), typeMirror)) {
        wrongTypes.add(typeMirror.toString());
      } else {
        types.add(typeMirror.toString());
      }
    }

    if (!wrongTypes.isEmpty()) {
      processing().getMessager().printMessage(
          Diagnostic.Kind.ERROR,
          "@Metainf.Service(value = {...}) contains types that are not implemented by "
              + typeElement.getSimpleName()
              + ": " + wrongTypes,
          typeElement,
          AnnotationMirrors.findAnnotation(typeElement.getAnnotationMirrors(), Metainf.Service.class));
    }

    return FluentIterable.from(types).toSet();
  }

  @Nullable
  private TypeElement validated(Element element) {
    Element enclosingElement = element.getEnclosingElement();

    if (element.getKind() == ElementKind.CLASS
        && element.getModifiers().contains(Modifier.PUBLIC)
        && !element.getModifiers().contains(Modifier.ABSTRACT)
        && enclosingElement != null
        && enclosingElement.getKind() == ElementKind.PACKAGE
        && !((PackageElement) enclosingElement).isUnnamed()) {
      return (TypeElement) element;
    }

    processing().getMessager()
        .printMessage(Diagnostic.Kind.ERROR,
            "Element annotated with @Metainf.Service annotation should be public top-level non-abstract class in a package",
            element);

    return null;
  }
}

@@ -2047,64 +2047,129 @@
     
-builder.putAll(typeElement.getQualifiedName().toString()
+String binaryName = processing().getElementUtils().getBinaryName(typeElement).toString();%0A      builder.putAll(binaryName
 , in
@@ -4206,16 +4206,118 @@
       &&
+ enclosingElement != null) %7B%0A%0A      if (enclosingElement.getKind() == ElementKind.PACKAGE%0A          &&
  !elemen
@@ -4373,47 +4373,122 @@
     
+  
 && 
-enclosingElement != null%0A        && 
+!((PackageElement) enclosingElement).isUnnamed()) %7B%0A        return (TypeElement) element;%0A      %7D%0A%0A      if (
 encl
@@ -4521,32 +4521,31 @@
 ElementKind.
-PACKAGE%0A
+CLASS%0A 
         && !
@@ -4547,60 +4547,64 @@
  && 
-!((PackageElement) enclosingElement).isUnnamed(
+element.getModifiers().contains(Modifier.STATIC
 )) %7B%0A
+    
     
@@ -4631,24 +4631,32 @@
 t) element;%0A
+      %7D%0A
     %7D%0A%0A    p
@@ -4830,16 +4830,26 @@
 bstract 
+or static 
 class in

Allow Metainf.Service annotation on static nested classes