package de.renew.gui.pnml.parser;

import java.lang.reflect.InvocationTargetException;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import CH.ifa.draw.framework.FigureWithID;
import de.renew.gui.TransitionFigure;
import de.renew.gui.pnml.converter.NetConverter;
import de.renew.plugin.PluginManager;


/**
 * parse and create Transitions
 */
public class TransitionParser extends NodeParser {
    private static final org.apache.log4j.Logger logger =
        org.apache.log4j.Logger.getLogger(TransitionParser.class);
    private String subtypeClass = null;

    public TransitionParser(Element node, NetConverter converter) {
        super(node, converter);

        // Check to see if there is any transition subtype information present.
        // This information is later used to instantiate the right TransitionFigure subclass.
        // E.g. this is the case for workflow tasks.
        final NodeList toolspecificEles = node.getElementsByTagName("toolspecific");
        for (int i = 0; i < toolspecificEles.getLength(); i++) {
            final NodeList subtypeEles =
                ((Element) toolspecificEles.item(i)).getElementsByTagName("subtype");
            final int length = subtypeEles.getLength();

            if (length > 0) {
                if (length > 1) {
                    // Note that this does not catch the case that another subtype element is is a different toolspecific element.
                    logger.warn(
                        TransitionParser.class.getSimpleName()
                            + ": more than one subtype element.");
                }
                final Element subtype = (Element) subtypeEles.item(0);

                subtypeClass = subtype.getAttribute("class");
                return;
            }
        }
    }

    @Override
    public FigureWithID createObject() {
        if (subtypeClass != null) {
            try {
                // Try to instantiated the given transition subtype class.
                return (FigureWithID) Class
                    .forName(subtypeClass, true, PluginManager.getInstance().getBottomClassLoader())
                    .getConstructor().newInstance();
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                | IllegalArgumentException | InvocationTargetException | NoSuchMethodException
                | SecurityException e) {
                logger.error(
                    TransitionParser.class.getSimpleName() + ": " + e.getLocalizedMessage(), e);
            }
        }

        return new TransitionFigure();
    }
}