/*
 * Copyright 2013 Google Inc.
 *
 * 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 com.google.web.bindery.requestfactory.gwt.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.junit.client.GWTTestCase;
import com.google.web.bindery.event.shared.SimpleEventBus;
import com.google.web.bindery.requestfactory.shared.RequestTransport;
import com.google.web.bindery.requestfactory.shared.SimpleJsonRpcRequestFactory;
import com.google.web.bindery.requestfactory.shared.SimpleJsonRpcRequestFactory.SimpleContext.FooRequest;

import java.util.Arrays;
import java.util.List;

/**
 * Class to test some edge-cases of
 * {@link com.google.web.bindery.requestfactory.shared.JsonRpcService}s generated by
 * {@link com.google.web.bindery.requestfactory.gwt.rebind.RequestFactoryGenerator}.
 */
public class JsonRpcRequestFactoryTest extends GWTTestCase {

  @Override
  public String getModuleName() {
    return "com.google.web.bindery.requestfactory.gwt.RequestFactorySuite";
  }

  public void testEnumsUsedAsTypeParameter() {
    String[] expectedPayloadRegexes = new String[] {
        ".*\"method\":\"simple.foo\".*",
        ".*\"params\":\\{\"enums\":\\[\"VALUE\"\\]\\}.*" };
    List<FooRequest.FooEnum> list =
        Arrays.asList(new FooRequest.FooEnum[] {FooRequest.FooEnum.VALUE});
    createFactory(expectedPayloadRegexes).simple().foo().setEnums(list).fire();
  }

  protected SimpleJsonRpcRequestFactory createFactory() {
    return GWT.create(SimpleJsonRpcRequestFactory.class);
  }

  private SimpleJsonRpcRequestFactory createFactory(final String[] expectedPayloadRegexes) {
    SimpleJsonRpcRequestFactory req = createFactory();
    req.initialize(new SimpleEventBus(), new RequestTransport() {
      @Override
      public void send(String payload, TransportReceiver receiver) {
        stringMatchesRegexes(payload, expectedPayloadRegexes);
      }
    });
    return req;
  }

  private static void stringMatchesRegexes(String string, String[] regexes) {
    for (String regex : regexes) {
      assertTrue("String \"" + string + "\" did not match \"" + regex + "\"",
          string.matches(regex));
    }
  }
}

