package net.wouterdanes.docker.remoteapi;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;

import net.wouterdanes.docker.remoteapi.exception.DockerException;
import net.wouterdanes.docker.remoteapi.model.DockerVersionInfo;

/**
 * The class act as an interface to the "root" Remote Docker API with some "misc" service end points.
 */
public class MiscService extends BaseService {

    private static final Pattern BUILD_IMAGE_ID_EXTRACTION_PATTERN =
            Pattern.compile(".*Successfully built ([0-9a-f]+).*", Pattern.DOTALL);

    public MiscService(final String dockerApiRoot) {
        super(dockerApiRoot, "/");
    }

    /**
     * Returns the Docker version information
     *
     * @return a {@link DockerVersionInfo} instance describing this docker installation.
     */
    public DockerVersionInfo getVersionInfo() {
        String json = getServiceEndPoint()
                .path("/version")
                .request(MediaType.APPLICATION_JSON_TYPE)
                .get(String.class);

        return toObject(json, DockerVersionInfo.class);
    }

    public String buildImage(byte[] tarArchive) {
        String jsonStream = getServiceEndPoint()
                .path("/build")
                .queryParam("q", true)
                .request(MediaType.APPLICATION_JSON_TYPE)
                .post(Entity.entity(tarArchive, "application/tar"), String.class);

        Matcher matcher = BUILD_IMAGE_ID_EXTRACTION_PATTERN.matcher(jsonStream);
        if (!matcher.matches()) {
            throw new DockerException("Can't obtain ID from build output stream.", jsonStream);
        }

        return matcher.group(1);
    }

}
@@ -611,24 +611,241 @@
 n.DOTALL);%0A%0A
+    private static final Pattern BUILD_IMAGE_INTERMEDIATE_IDS_EXTRACTION_PATTERN =%0A            Pattern.compile(%22.*?Running in (%5B0-9a-f%5D+).*?%22, Pattern.DOTALL);%0A%0A    private final ContainersService containersService;%0A%0A
     public M
@@ -920,16 +920,82 @@
 , %22/%22);%0A
+        containersService = new ContainersService(dockerApiRoot);%0A
     %7D%0A%0A 
@@ -1738,32 +1738,306 @@
 String.class);%0A%0A
+        Matcher intermediates = BUILD_IMAGE_INTERMEDIATE_IDS_EXTRACTION_PATTERN.matcher(jsonStream);%0A        while (intermediates.find()) %7B%0A            String intermediateId = intermediates.group(1);%0A            containersService.deleteContainer(intermediateId);%0A        %7D%0A%0A
         Matcher 
@@ -2233,33 +2233,32 @@
 eam);%0A        %7D%0A
-%0A
         return m

Remove intermediate containers after a build.