package uk.ac.ebi.quickgo.annotation.validation;

import uk.ac.ebi.quickgo.annotation.validation.model.DBXRefEntity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.batch.item.ItemWriter;

/**
 * @author Tony Wardell
 * Date: 08/11/2016
 * Time: 14:41
 * Created with IntelliJ IDEA.
 */
public class DBXRefEntityValidation implements ConstraintValidator<WithFromValidator, String[]> {

    private final static Map<String, List<DBXRefEntity>> mappedEntities = new HashMap<>();

    @Override public void initialize(WithFromValidator constraintAnnotation) {

    }

    @Override public boolean isValid(String[] values, ConstraintValidatorContext context) {
        return values == null ? true : Stream.of(values)
                .allMatch(this::valueIsValid);
    }

    private boolean valueIsValid(String value) {
        if( value.contains(":")){
            return (isValidForDb(value));
        }else{
            return true;
        }
    }

    private boolean isValidForDb(String value) {
        final String dbKey = value.substring(0, value.indexOf(":")).toLowerCase();
        final String id = value.substring(value.indexOf(":")+1);
        List<DBXRefEntity> entities = mappedEntities.get(dbKey);

        if(entities!=null){
            for(DBXRefEntity entity : entities){
                if(entity.test(id)){
                    return true;
                }
            }
        }
        return false;
    }

    static class DBXRefEntityAggregator implements ItemWriter<DBXRefEntity> {

        @Override public void write(List<? extends DBXRefEntity> items) throws Exception {

            for (DBXRefEntity item : items) {
                mappedEntities.computeIfAbsent(item.database.toLowerCase(), k -> new ArrayList<>()).add(item);
            }
        }
    }
}

@@ -394,16 +394,160 @@
 r;%0A%0A/**%0A
+ * Use the database cross reference information contain in this class to verify a list of potential database cross%0A * reference identifiers.%0A *%0A
  * @auth
@@ -562,16 +562,16 @@
 Wardell%0A
-
  * Date:
@@ -906,24 +906,352 @@
 ) %7B%0A%0A    %7D%0A%0A
+    /**%0A     * If the entire list of values passed to isValid can be successfully validated, or not validated at all then%0A     * isValid will return true.%0A     * @param values list of potential database cross reference identifiers.%0A     * @param context of the isValid call.%0A     * @return validation result as boolean.%0A     */%0A
     @Overrid
@@ -1364,16 +1364,10 @@
 ull 
-? true :
+%7C%7C
  Str
@@ -1496,12 +1496,16 @@
     
-if( 
+return !
 valu
@@ -1523,29 +1523,11 @@
 %22:%22)
-)%7B%0A            return
+ %7C%7C
  (is
@@ -1550,58 +1550,8 @@
 ));%0A
-        %7Delse%7B%0A            return true;%0A        %7D%0A
     

Add javadoc.