package org.modelio.junit.impl;

import java.util.ArrayList;
import java.util.List;
import org.modelio.api.modelio.model.IModelingSession;
import org.modelio.api.modelio.model.ITransaction;
import org.modelio.api.modelio.model.event.IElementDeletedEvent;
import org.modelio.api.modelio.model.event.IModelChangeEvent;
import org.modelio.api.modelio.model.event.IModelChangeHandler;
import org.modelio.vcore.smkernel.mapi.MObject;


public class JUnitModelChangeHandler implements IModelChangeHandler {

    public void handleModelChange(IModelingSession session, IModelChangeEvent event) {
        TestModelUpdater updater = new TestModelUpdater();
        
        // Memorize the parents to be updated
        List<MObject> parentsToUpdate = new ArrayList<>();
        for (IElementDeletedEvent deletedElement : event.getDeleteEvents()) {
            if (!parentsToUpdate.contains(deletedElement.getOldParent())) {
                parentsToUpdate.add(deletedElement.getOldParent());
            }
        }
        
        // Visit the elements to delete
        try (ITransaction t = session.createTransaction("Update the test hierarchy")) {
            boolean modelUpdated = false;
            for (MObject parent : parentsToUpdate) {
                if (((Boolean) parent.accept(updater)) == true) {
                    modelUpdated = true;
                }
            }
        
            // If the model has changed, the transaction is commited.
            if (modelUpdated) {
                t.commit();
            } else {
                t.rollback();
            }
        }
    }
}