/*
 * Copyright 2015
 * Ubiquitous Knowledge Processing (UKP) Lab and FG Language Technology
 * Technische Universität Darmstadt
 *
 * 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 de.tudarmstadt.ukp.clarin.webanno.diag.repairs;

import static de.tudarmstadt.ukp.clarin.webanno.api.WebAnnoConst.RELATION_TYPE;
import static de.tudarmstadt.ukp.clarin.webanno.diag.CasDoctorUtils.getNonIndexedFSes;

import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.uima.cas.CAS;
import org.apache.uima.cas.Feature;
import org.apache.uima.cas.FeatureStructure;
import org.apache.uima.cas.Type;
import org.apache.uima.cas.text.AnnotationFS;
import org.springframework.beans.factory.annotation.Autowired;

import de.tudarmstadt.ukp.clarin.webanno.api.AnnotationSchemaService;
import de.tudarmstadt.ukp.clarin.webanno.api.WebAnnoConst;
import de.tudarmstadt.ukp.clarin.webanno.diag.repairs.Repair.Safe;
import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationLayer;
import de.tudarmstadt.ukp.clarin.webanno.model.Project;
import de.tudarmstadt.ukp.clarin.webanno.support.logging.LogLevel;
import de.tudarmstadt.ukp.clarin.webanno.support.logging.LogMessage;

/**
 * Removes relations that were not properly cleaned up after deleting a source/target span. Such
 * relations still point to the respective span even through the span is not indexed anymore.
 */
@Safe(false)
public class RemoveDanglingRelationsRepair
    implements Repair
{
    private @Autowired AnnotationSchemaService annotationService;
    
    @Override
    public void repair(Project aProject, CAS aCas, List<LogMessage> aMessages)
    {
        Set<FeatureStructure> nonIndexed = getNonIndexedFSes(aCas);
        
        Set<FeatureStructure> toDelete = new LinkedHashSet<>();
        
        Map<String, AnnotationLayer> layerCache = new HashMap<>();
        
        for (AnnotationFS fs : aCas.getAnnotationIndex()) {
            Type t = fs.getType();

            AnnotationLayer layer = layerCache.computeIfAbsent(t.getName(),
                k -> annotationService.findLayer(aProject, k));

            // Is this a relation?
            if (!RELATION_TYPE.equals(layer.getType())) {
                continue;
            }

            Feature sourceFeat = t.getFeatureByBaseName(WebAnnoConst.FEAT_REL_SOURCE);
            Feature targetFeat = t.getFeatureByBaseName(WebAnnoConst.FEAT_REL_TARGET);
            
            FeatureStructure source = fs.getFeatureValue(sourceFeat);
            FeatureStructure target = fs.getFeatureValue(targetFeat);
            
            // Does it point to deleted spans?
            if (nonIndexed.contains(source) || nonIndexed.contains(target)) {
                toDelete.add(fs);
            }
        }

        // Delete those relations that pointed to deleted spans
        if (!toDelete.isEmpty()) {
            toDelete.forEach(aCas::removeFsFromIndexes);
            aMessages.add(new LogMessage(this, LogLevel.INFO, "Removed [%d] dangling relations.",
                    nonIndexed.size()));
        }
    }
}

@@ -742,88 +742,8 @@
 s;%0A%0A
-import static de.tudarmstadt.ukp.clarin.webanno.api.WebAnnoConst.RELATION_TYPE;%0A
 impo
@@ -830,34 +830,8 @@
 s;%0A%0A
-import java.util.HashMap;%0A
 impo
@@ -885,30 +885,8 @@
 st;%0A
-import java.util.Map;%0A
 impo
@@ -1100,141 +1100,8 @@
 FS;%0A
-import org.springframework.beans.factory.annotation.Autowired;%0A%0Aimport de.tudarmstadt.ukp.clarin.webanno.api.AnnotationSchemaService;
 %0Aimp
@@ -1227,72 +1227,8 @@
 fe;%0A
-import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationLayer;%0A
 impo
@@ -1699,79 +1699,8 @@
 r%0A%7B%0A
-    private @Autowired AnnotationSchemaService annotationService;%0A    %0A
     
@@ -1948,84 +1948,8 @@
    %0A
-        Map%3CString, AnnotationLayer%3E layerCache = new HashMap%3C%3E();%0A        %0A
     
@@ -2039,17 +2039,16 @@
 Type();%0A
-%0A
         
@@ -2055,270 +2055,8 @@
     
-AnnotationLayer layer = layerCache.computeIfAbsent(t.getName(),%0A                k -%3E annotationService.findLayer(aProject, k));%0A%0A            // Is this a relation?%0A            if (!RELATION_TYPE.equals(layer.getType())) %7B%0A                continue;%0A            %7D%0A
 %0A   
@@ -2231,32 +2231,183 @@
 );%0A            %0A
+            // Is this a relation?%0A            if (!(sourceFeat != null && targetFeat != null)) %7B%0A                continue;%0A            %7D%0A            %0A
             Feat

Revert "#1492 - Rely on layer type instead of feature presence for relation repair action"