/*
    Copyright 2014 Wouter Danes

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

package net.wouterdanes.docker.remoteapi;

import net.wouterdanes.docker.remoteapi.model.ImageDescriptor;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Optional;

/**
 * This class is responsible for talking to the Docker Remote API "images" endpoint.<br> See <a
 * href="http://docs.docker.io/reference/api/docker_remote_api_v1.12/#22-images">
 * http://docs.docker.io/reference/api/docker_remote_api_v1.12/#22-images</a>
 */
public class ImagesService extends BaseService {

    public ImagesService(String dockerApiRoot) {
        super(dockerApiRoot, "/images");
    }

    public void deleteImage(final String imageId) {
        try {
            getServiceEndPoint()
                    .path(imageId)
                    .request(MediaType.APPLICATION_JSON_TYPE)
                    .delete(String.class);
        } catch (WebApplicationException e) {
            throw makeImageTargetingException("Cannot remove image", e);
        }
    }

    public String pullImage(final String image) {
        ImageDescriptor descriptor = new ImageDescriptor(image);

        WebTarget target = getServiceEndPoint()
                .path("create");

        target = target.queryParam("fromImage", descriptor.getRegistryRepositoryAndImage());

        if (descriptor.getTag().isPresent()) {
            target = target.queryParam("tag", descriptor.getTag().get());
        }

        return target.request()
                .header(REGISTRY_AUTH_HEADER, getRegistryAuthHeaderValue())
                .accept(MediaType.APPLICATION_JSON_TYPE)
                .post(null, String.class);
    }

    public String pushImage(String nameAndTag) {
        try {
            WebTarget target = createPushRequestFromTag(nameAndTag);

            return target.request()
                    .header(REGISTRY_AUTH_HEADER, getRegistryAuthHeaderValue())
                    .accept(MediaType.APPLICATION_JSON_TYPE)
                    .post(null, String.class);

        } catch (WebApplicationException e) {
            throw makeImageTargetingException(nameAndTag, e);

        }
    }

    public void tagImage(final String imageId, final String nameAndTag) {
        ImageDescriptor descriptor = new ImageDescriptor(nameAndTag);

        WebTarget target = getServiceEndPoint()
                .path(imageId)
                .path("tag")
                .queryParam("repo", descriptor.getRegistryRepositoryAndImage())
                .queryParam("force", 1);

        Optional<String> targetTag = descriptor.getTag();
        if (targetTag.isPresent()) {
            target = target.queryParam("tag", targetTag.get());
        }

        Response response = target.request()
                .accept(MediaType.APPLICATION_JSON_TYPE)
                .post(null);

        Response.StatusType statusInfo = response.getStatusInfo();

        response.close();

        checkImageTargetingResponse(imageId, statusInfo);
    }

    private WebTarget createPushRequestFromTag(final String nameAndTag) {
        ImageDescriptor descriptor = new ImageDescriptor(nameAndTag);
        WebTarget target = getServiceEndPoint()
                .path(descriptor.getRegistryRepositoryAndImage())
                .path("push");

        if (descriptor.getTag().isPresent()) {
            target = target.queryParam("tag", descriptor.getTag().get());
        }

        return target;
    }
}

@@ -633,16 +633,128 @@
 teapi;%0A%0A
+import com.google.gson.JsonElement;%0Aimport com.google.gson.JsonObject;%0Aimport com.google.gson.JsonStreamParser;%0A
 import n
@@ -808,16 +808,16 @@
 riptor;%0A
-
 %0Aimport 
@@ -959,16 +959,109 @@
 sponse;%0A
+import java.io.BufferedReader;%0Aimport java.io.InputStream;%0Aimport java.io.InputStreamReader;%0A
 import j
@@ -2290,38 +2290,51 @@
      %7D%0A%0A        
-return
+Response response =
  target.request(
@@ -2494,30 +2494,908 @@
 ost(null
-, String.class
+);%0A%0A        InputStream inputStream = (InputStream) response.getEntity();%0A%0A        parseSteamToDisplayImageDownloadStatus(inputStream);%0A%0A        return response.readEntity(String.class);%0A    %7D%0A%0A    private static void parseSteamToDisplayImageDownloadStatus(final InputStream inputStream) %7B%0A        InputStreamReader isr = new InputStreamReader(inputStream);%0A        BufferedReader reader = new BufferedReader(isr);%0A%0A        JsonStreamParser parser = new JsonStreamParser(reader);%0A%0A        while (parser.hasNext()) %7B%0A            JsonElement element = parser.next();%0A            JsonObject object = element.getAsJsonObject();%0A            if (object.has(%22status%22)) %7B%0A                System.out.print(%22.%22);%0A            %7D%0A            if (object.has(%22error%22)) %7B%0A                System.err.println(%22ERROR: %22 + object.get(%22error%22).getAsString());%0A            %7D%0A        %7D%0A        System.out.println(%22%22
 );%0A    %7D

Add some feedback when pulling images so it doesn't look like the plugin has hung.