package org.hildan.livedoc.core.builders.doc;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.hildan.livedoc.core.annotations.ApiError;
import org.hildan.livedoc.core.annotations.ApiErrors;
import org.hildan.livedoc.core.pojo.ApiErrorDoc;

import static java.util.stream.Collectors.toList;

public class ApiErrorDocReader {

    public static List<ApiErrorDoc> build(Method method) {
        List<ApiErrorDoc> apiMethodDocs = new ArrayList<>();

        ApiErrors methodAnnotation = method.getAnnotation(ApiErrors.class);
        ApiErrors typeAnnotation = method.getDeclaringClass().getAnnotation(ApiErrors.class);

        if (methodAnnotation != null) {
            apiMethodDocs.addAll(readApiErrorDocs(methodAnnotation));
        }

        if (typeAnnotation != null) {
            List<String> alreadyUsedCodes = apiMethodDocs.stream().map(ApiErrorDoc::getCode).collect(toList());
            List<ApiErrorDoc> apiMethodDocs2 = readApiErrorDocs(typeAnnotation);
            apiMethodDocs2.removeIf(errDoc -> alreadyUsedCodes.contains(errDoc.getCode()));
            apiMethodDocs.addAll(apiMethodDocs2);
        }
        return apiMethodDocs;
    }

    private static List<ApiErrorDoc> readApiErrorDocs(ApiErrors annotation) {
        List<ApiErrorDoc> errorDocs = new ArrayList<>();
        for (ApiError error : annotation.apierrors()) {
            errorDocs.add(new ApiErrorDoc(error.code(), error.description()));
        }
        return errorDocs;
    }
}

@@ -451,30 +451,29 @@
 rrorDoc%3E api
-Method
+Error
 Docs = new A
@@ -705,38 +705,37 @@
 %0A            api
-Method
+Error
 Docs.addAll(read
@@ -859,30 +859,29 @@
 dCodes = api
-Method
+Error
 Docs.stream(
@@ -960,27 +960,43 @@
 Doc%3E api
-MethodDocs2
+ErrorDocsFromTypeAnnotation
  = readA
@@ -1039,27 +1039,43 @@
      api
-MethodDocs2
+ErrorDocsFromTypeAnnotation
 .removeI
@@ -1143,30 +1143,29 @@
          api
-Method
+Error
 Docs.addAll(
@@ -1171,19 +1171,35 @@
 (api
-MethodDocs2
+ErrorDocsFromTypeAnnotation
 );%0A 
@@ -1225,22 +1225,21 @@
 turn api
-Method
+Error
 Docs;%0A  

Fix variable names in ApiErrorDocReader