package marmalade.client.wire.tasks;

import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import marmalade.client.Response;

import org.apache.http.Header;

import com.google.common.base.Objects;

public class SerializableResponse implements Serializable
{
   private static final long serialVersionUID = 6522661301517225640L;

   private final byte[] bytes;
   private final int status;
   private final Map<String, String> headers;

   public SerializableResponse(Response response)
   {
      this.headers = new HashMap<String, String>();
      this.bytes = getBytes(response);
      this.status = response.status();

      Header[] allHeaders = response.getHttpResponse().getAllHeaders();
      for (Header h : allHeaders) {
         headers.put(h.getName(), h.getValue());
      }
   }

   public String asString()
   {
      return new String(bytes);
   }

   public byte[] getBytes()
   {
      return bytes;
   }

   public Map<String, String> getHeaders()
   {
      return Collections.unmodifiableMap(headers);
   }

   public int status()
   {
      return status;
   }

   @Override
   public String toString()
   {
      return Objects.toStringHelper(this).add("status", status).add("headers", headers).toString();
   }

   private byte[] getBytes(Response response)
   {
      try {
         return response.asBytes();
      } catch (Exception e) {
         return new byte[] {};
      }
   }
}

@@ -680,166 +680,30 @@
     
-Header%5B%5D allHeaders = response.getHttpResponse().getAllHeaders();%0A      for (Header h : allHeaders) %7B%0A         headers.put(h.getName(), h.getValue());%0A      %7D
+initHeaders(response);
 %0A   
@@ -1319,11 +1319,283 @@
   %7D%0A   %7D
+%0A%0A   private void initHeaders(Response response)%0A   %7B%0A      Header%5B%5D allHeaders = response.getHttpResponse().getAllHeaders();%0A      if (allHeaders != null) %7B%0A         for (Header h : allHeaders) %7B%0A            headers.put(h.getName(), h.getValue());%0A         %7D%0A      %7D%0A   %7D
 %0A%7D%0A

check null headers