package com.nedap.archie.paths;

import com.google.common.base.Joiner;

/**
 * Segment of an apath-query
 * Created by pieter.bos on 19/10/15.
 */
public class PathSegment {
    private final static Joiner expressionJoiner = Joiner.on(", ").skipNulls();

    private String nodeName;
    private String nodeId;
    private Integer index;

    public PathSegment(String nodeName, Integer index) {
        this(nodeName, null, index);
    }

    public PathSegment(String nodeName, String nodeId) {
        this(nodeName, nodeId, null);
    }

    public PathSegment(String nodeName) {
        this(nodeName, null, null);
    }

    public PathSegment(String nodeName, String nodeId, Integer index) {
        this.nodeName = nodeName;
        this.nodeId = nodeId;
        this.index = index;
    }

    public String getNodeName() {
        return nodeName;
    }

    public void setNodeName(String nodeName) {
        this.nodeName = nodeName;
    }

    public String getNodeId() {
        return nodeId;
    }

    public void setNodeId(String nodeId) {
        this.nodeId = nodeId;
    }

    public Integer getIndex() {
        return index;
    }

    public void setIndex(Integer index) {
        this.index = index;
    }

    public boolean hasIdCode() {
        return nodeId != null && nodeId.matches("id(\\.?\\d)+");
    }

    public boolean hasNumberIndex() { return index != null;}

    public boolean hasArchetypeRef() {
        return nodeId != null && nodeId.matches("(.*::)?.*-.*-.*\\..*\\.v.*");
    }

    @Override
    public String toString() {
        if(hasExpressions()) {
            return String.format("/%s[%s]", nodeName, expressionJoiner.join(nodeId, index));
        } else {
            return String.format("/%s", nodeName);
        }
    }

    public boolean hasExpressions() {
        return nodeId != null || index != null;
    }
}

@@ -65,16 +65,49 @@
 oiner;%0A%0A
+import java.util.regex.Pattern;%0A%0A
 /**%0A * S
@@ -281,16 +281,201 @@
 lls();%0A%0A
+    private static final Pattern archetypeRefPattern = Pattern.compile(%22(.*::)?.*-.*-.*%5C%5C..*%5C%5C.v.*%22);%0A    private static final Pattern nodeIdPattern = Pattern.compile(%22id(%5C%5C.?%5C%5Cd)+%22);%0A%0A
     priv
@@ -1519,31 +1519,40 @@
 deId
-.matches(%22id(%5C%5C.?%5C%5Cd)+%22
+Pattern.matcher(nodeId).matches(
 );%0A 
@@ -1691,22 +1691,51 @@
 null && 
+archetypeRefPattern.matcher(
 nodeId
+)
 .matches
@@ -1739,36 +1739,9 @@
 hes(
-%22(.*::)?.*-.*-.*%5C%5C..*%5C%5C.v.*%22
+)
 );%0A 
@@ -1845,42 +1845,31 @@
 urn 
-String.format(%22/%25s%5B%25s%5D%22, nodeName,
+%22/%22 + nodeName + %22%5B%22 + 
  exp
@@ -1901,17 +1901,22 @@
 , index)
-)
+ + %22%5D%22
 ;%0A      
@@ -1949,28 +1949,13 @@
 urn 
-String.format(%22/%25s%22,
+%22/%22 +
  nod
@@ -1959,17 +1959,16 @@
 nodeName
-)
 ;%0A      

Optimize PathSegment for more performance