/*
 * RpcResponse.java
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * This program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

package org.rstudio.core.client.jsonrpc;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;

public class RpcResponse extends JavaScriptObject
{
   protected RpcResponse()
   {
      
   }
   
   public final static RpcResponse parse(String json) 
   {      
      try
      {
         JSONValue val = JSONParser.parseStrict(json);
         return val.isObject().getJavaScriptObject().cast();
      }
      catch(Exception e)
      {
         return null;
      }
   }
    
   public final native static RpcResponse create(RpcError error) /*-{
      var response = new Object();
      response.error = error ;
      return response ;
   }-*/;
   
   public final RpcError getError()
   {
      return getField("error");
   }

   public final String getAsyncHandle()
   {
      return getField("asyncHandle");
   }
   
   public final <T> T getResult()
   {
      T field = this.<T>getField("result");
      return field;
   }

   private static Boolean wrapBoolean(boolean value)
   {
      return value;
   }
   
   public final native <T> T getField(String name) /*-{
      var value = this[name];
      if (typeof(value) == 'boolean')
         return @org.rstudio.core.client.jsonrpc.RpcResponse::wrapBoolean(Z)(value);
      return value;
   }-*/;
}

@@ -797,32 +797,157 @@
     try%0A      %7B%0A
+         // we first call parseStrict so we can use the browser%0A         // json parser (for performance) whenever possible)%0A
          JSONVal
@@ -1079,32 +1079,478 @@
 tion e)%0A      %7B%0A
+         try%0A         %7B%0A            // there are some cases where json emitted by our %0A            // server isn't parsable by parseStrict (for example,%0A            // see bug #3025). for these situations we call %0A            // parseLenient (which in turn calls eval)%0A            JSONValue val = JSONParser.parseLenient(json);%0A            return val.isObject().getJavaScriptObject().cast();%0A         %7D%0A         catch(Exception e2)%0A         %7B%0A   
          return 
@@ -1555,16 +1555,27 @@
 n null;%0A
+         %7D%0A
       %7D%0A

call parseLenient if parseStrict fails