package org.modelio.JUnit.impl;

import java.util.ArrayList;
import java.util.List;

import org.modelio.metamodel.uml.infrastructure.Dependency;
import org.modelio.metamodel.uml.infrastructure.Element;
import org.modelio.metamodel.uml.statik.Class;
import org.modelio.metamodel.uml.statik.Package;
import org.modelio.metamodel.visitors.DefaultInfrastructureVisitor;
import org.modelio.metamodel.visitors.DefaultModelVisitor;


public class TestModelUpdater extends DefaultModelVisitor {

    public TestModelUpdater() {
        super(new DefaultInfrastructureVisitor() {
            @Override
            /*
             * Return false for all non package visits
             */
            public Object visitElement(Element obj) {
                return Boolean.FALSE;
            }
        });
    }

    @Override
    public Object visitPackage(Package obj) {
        List toDelete = new ArrayList<>();
        
        for (Class c : obj.getOwnedElement(Class.class)) {
            // Check all owned test cases
            if (c.isStereotyped("JUnit", "JUnit")) {
                boolean hasTestedClass = false;
                // Check that there is a link towards a tested class
                for (Dependency dep : c.getDependsOnDependency()) {
                    if (dep.isStereotyped("JUnit", "JUnitDependency")) {
                        hasTestedClass = true;
                    }
                }
        
                // No tested class means the test case must be deleted
                if (hasTestedClass == false) {
                    toDelete.add(c);
                }
            }
        }
        
        if (toDelete.isEmpty()) {
            return Boolean.FALSE;
        } else {
            // Delete orphan test cases
            for (Class c : toDelete) {
                c.delete();
            }
            return Boolean.TRUE;
        }
    }
}