/**
 * Licensed to jclouds, Inc. (jclouds) under one or more
 * contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  jclouds licenses this file
 * to you 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 org.jclouds.openstack.swift.functions;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.SortedSet;

import javax.inject.Inject;
import javax.inject.Provider;
import javax.ws.rs.core.UriBuilder;

import org.jclouds.blobstore.domain.PageSet;
import org.jclouds.blobstore.domain.internal.PageSetImpl;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.functions.ParseJson;
import org.jclouds.json.Json;
import org.jclouds.openstack.swift.domain.ObjectInfo;
import org.jclouds.openstack.swift.domain.internal.ObjectInfoImpl;
import org.jclouds.openstack.swift.options.ListContainerOptions;
import org.jclouds.rest.InvocationContext;
import org.jclouds.rest.internal.GeneratedHttpRequest;

import com.google.common.base.Function;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.gson.reflect.TypeToken;
import com.google.inject.TypeLiteral;

/**
 * This parses {@link ObjectInfo} from a gson string.
 * 
 * @author Adrian Cole
 */
public class ParseObjectInfoListFromJsonResponse extends ParseJson<PageSet<ObjectInfo>> implements
         InvocationContext<ParseObjectInfoListFromJsonResponse> {
   private final Provider<UriBuilder> uriBuilders;

   private GeneratedHttpRequest<?> request;
   private String container;

   @Inject
   public ParseObjectInfoListFromJsonResponse(Json json, Provider<UriBuilder> uriBuilders) {
      super(json, new TypeLiteral<PageSet<ObjectInfo>>() {
      });
      this.uriBuilders = uriBuilders;
   }

   public PageSet<ObjectInfo> apply(InputStream stream) {
      checkState(request != null, "request should be initialized at this point");
      checkState(request.getArgs() != null, "request.getArgs() should be initialized at this point");
      checkArgument(request.getArgs().get(0) instanceof String, "arg[0] must be a container name");
      checkArgument(request.getArgs().get(1) instanceof ListContainerOptions[],
               "arg[1] must be an array of ListContainerOptions");
      ListContainerOptions[] optionsList = (ListContainerOptions[]) request.getArgs().get(1);
      ListContainerOptions options = optionsList.length > 0 ? optionsList[0] : ListContainerOptions.NONE;
      Type listType = new TypeToken<SortedSet<ObjectInfoImpl>>() {
      }.getType();

      try {
         SortedSet<ObjectInfoImpl> list = apply(stream, listType);
         SortedSet<ObjectInfo> returnVal = Sets.newTreeSet(Iterables.transform(list,
                  new Function<ObjectInfoImpl, ObjectInfo>() {
                     public ObjectInfo apply(ObjectInfoImpl from) {
                        return from.toBuilder().container(container).uri(
                                 uriBuilders.get().uri(request.getEndpoint()).path(from.getName()).replaceQuery("")
                                          .build()).build();
                     }
                  }));
         boolean truncated = options.getMaxResults() == returnVal.size();
         String marker = truncated ? returnVal.last().getName() : null;
         return new PageSetImpl<ObjectInfo>(returnVal, marker);
      } catch (IOException e) {
         throw new RuntimeException("problem reading response from request: " + request, e);
      }
   }

   @Override
   public ParseObjectInfoListFromJsonResponse setContext(HttpRequest request) {
      checkArgument(request instanceof GeneratedHttpRequest<?>, "note this handler requires a GeneratedHttpRequest");
      this.request = (GeneratedHttpRequest<?>) request;
      return setContainer(GeneratedHttpRequest.class.cast(request).getArgs().get(0).toString());
   }

   private ParseObjectInfoListFromJsonResponse setContainer(String container) {
      this.container = container;
      return this;
   }
}
