package de.renew.gui.pnml.parser;

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

import CH.ifa.draw.figures.TextFigure;
import de.renew.gui.pnml.converter.NetConverter;


/**
 * parse Annotations
 */
public class AnnotationParser extends ElementParser {
    private static final org.apache.log4j.Logger logger =
        org.apache.log4j.Logger.getLogger(AnnotationParser.class);
    private String _text;
    private int _offSetX = 0;
    private int _offSetY = 0;

    /**Create an XMLParser that parses PNML annotations
     * @param annotation XML element to parse
     */
    public AnnotationParser(Element annotation, NetConverter converter) {
        super(annotation, converter);
    }

    /**
     * Parse the annotation saved with this object and save the values found
     */
    @Override
    protected void doParse() {
        NodeList texte = getElement().getElementsByTagName("text");
        if (texte.getLength() == 0) {
            texte = getElement().getElementsByTagName("value");
        }
        for (int pos = 0; pos < texte.getLength(); pos++) {
            Element textEle = (Element) texte.item(pos);
            Text text = (Text) textEle.getFirstChild();
            if (text != null) {
                _text = text.getData();
            }
        }
        NodeList graphics = getElement().getElementsByTagName("graphics");
        for (int pos = 0; pos < graphics.getLength(); pos++) {
            Element graphic = (Element) graphics.item(pos);
            GraphicParser parser = new GraphicParser(graphic, getNetConverter());
            parser.parse();
            _offSetX = parser.offsetX();
            _offSetY = parser.offsetY();
        }
    }

    /**
     * The TextFigure object returned represents the annotation that has been parsed
     * <p>
     * This method requires that parse has been called before.
     * </p>
     * @return a renew TextFigure
     */
    public TextFigure getFigure() {
        NetConverter con = getNetConverter();
        TextFigure textFig = con.convertAnnotationToTextFigure(getElement());
        if (_text == null) {
            if (logger.isDebugEnabled()) {
                logger.debug(
                    AnnotationParser.class.getSimpleName()
                        + ": PMNL text figure without text ignored: "
                        + textFig.getClass().getSimpleName());
            }

            return null;
        }

        textFig.setText(_text);
        textFig.moveBy(_offSetX, _offSetY);
        if (logger.isDebugEnabled()) {
            logger.debug(
                AnnotationParser.class.getSimpleName() + ": PMNL text figure detected: "
                    + textFig.getClass().getSimpleName() + " " + textFig.getText());
        }
        return textFig;
    }
}