package org.activemq.ws.notification.impl;

import org.activemq.message.ActiveMQTopic;
import org.activemq.ws.xmlbeans.notification.base.TopicExpressionType;
import org.apache.xmlbeans.XmlCursor;

public class TopicExpressionConverter {

    private static final String SIMPLE_DIALECT = "http://www.ibm.com/xmlns/stdwip/web-services/WSTopics/TopicExpression/simple";
    
    static public TopicExpressionType toTopicExpression( ActiveMQTopic topic ) {
        TopicExpressionType rc = TopicExpressionType.Factory.newInstance();
        rc.setDialect(SIMPLE_DIALECT);
        XmlCursor cursor = rc.newCursor();
        cursor.setTextValue(topic.getPhysicalName());
        return rc;
    }
    
    static public ActiveMQTopic toActiveMQTopic(TopicExpressionType[] topicArray) {
        if( topicArray==null || topicArray.length==0 )
            return null;
        
        ActiveMQTopic childrenDestinations[] = new ActiveMQTopic[topicArray.length];
        for (int i = 0; i < topicArray.length; i++) {
            childrenDestinations[i] = toActiveMQTopic(topicArray[i]);
        }
        
        ActiveMQTopic topic = new ActiveMQTopic();
        topic.setChildDestinations(childrenDestinations);
        return topic;
    }

    static public ActiveMQTopic toActiveMQTopic( TopicExpressionType topic ) {
        String dialect = topic.getDialect();
        if( SIMPLE_DIALECT.equals(dialect) ) {
            
            XmlCursor cursor = topic.newCursor();
            //cursor.toFirstContentToken();
            String textValue = cursor.getTextValue();            
            return new ActiveMQTopic(textValue);
            
        } else {
            throw new RuntimeException("Topic dialect: "+dialect+" not supported");
        }
    }
            
}
