/**
 *                                  Apache License
 *                            Version 2.0, January 2004
 *                         http://www.apache.org/licenses/
 *
 *    TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
 *
 *    1. Definitions.
 *
 *       "License" shall mean the terms and conditions for use, reproduction,
 *       and distribution as defined by Sections 1 through 9 of this document.
 *
 *       "Licensor" shall mean the copyright owner or entity authorized by
 *       the copyright owner that is granting the License.
 *
 *       "Legal Entity" shall mean the union of the acting entity and all
 *       other entities that control, are controlled by, or are under common
 *       control with that entity. For the purposes of this definition,
 *       "control" means (i) the power, direct or indirect, to cause the
 *       direction or management of such entity, whether by contract or
 *       otherwise, or (ii) ownership of fifty percent (50%) or more of the
 *       outstanding shares, or (iii) beneficial ownership of such entity.
 *
 *       "You" (or "Your") shall mean an individual or Legal Entity
 *       exercising permissions granted by this License.
 *
 *       "Source" form shall mean the preferred form for making modifications,
 *       including but not limited to software source code, documentation
 *       source, and configuration files.
 *
 *       "Object" form shall mean any form resulting from mechanical
 *       transformation or translation of a Source form, including but
 *       not limited to compiled object code, generated documentation,
 *       and conversions to other media types.
 *
 *       "Work" shall mean the work of authorship, whether in Source or
 *       Object form, made available under the License, as indicated by a
 *       copyright notice that is included in or attached to the work
 *       (an example is provided in the Appendix below).
 *
 *       "Derivative Works" shall mean any work, whether in Source or Object
 *       form, that is based on (or derived from) the Work and for which the
 *       editorial revisions, annotations, elaborations, or other modifications
 *       represent, as a whole, an original work of authorship. For the purposes
 *       of this License, Derivative Works shall not include works that remain
 *       separable from, or merely link (or bind by name) to the interfaces of,
 *       the Work and Derivative Works thereof.
 *
 *       "Contribution" shall mean any work of authorship, including
 *       the original version of the Work and any modifications or additions
 *       to that Work or Derivative Works thereof, that is intentionally
 *       submitted to Licensor for inclusion in the Work by the copyright owner
 *       or by an individual or Legal Entity authorized to submit on behalf of
 *       the copyright owner. For the purposes of this definition, "submitted"
 *       means any form of electronic, verbal, or written communication sent
 *       to the Licensor or its representatives, including but not limited to
 *       communication on electronic mailing lists, source code control systems,
 *       and issue tracking systems that are managed by, or on behalf of, the
 *       Licensor for the purpose of discussing and improving the Work, but
 *       excluding communication that is conspicuously marked or otherwise
 *       designated in writing by the copyright owner as "Not a Contribution."
 *
 *       "Contributor" shall mean Licensor and any individual or Legal Entity
 *       on behalf of whom a Contribution has been received by Licensor and
 *       subsequently incorporated within the Work.
 *
 *    2. Grant of Copyright License. Subject to the terms and conditions of
 *       this License, each Contributor hereby grants to You a perpetual,
 *       worldwide, non-exclusive, no-charge, royalty-free, irrevocable
 *       copyright license to reproduce, prepare Derivative Works of,
 *       publicly display, publicly perform, sublicense, and distribute the
 *       Work and such Derivative Works in Source or Object form.
 *
 *    3. Grant of Patent License. Subject to the terms and conditions of
 *       this License, each Contributor hereby grants to You a perpetual,
 *       worldwide, non-exclusive, no-charge, royalty-free, irrevocable
 *       (except as stated in this section) patent license to make, have made,
 *       use, offer to sell, sell, import, and otherwise transfer the Work,
 *       where such license applies only to those patent claims licensable
 *       by such Contributor that are necessarily infringed by their
 *       Contribution(s) alone or by combination of their Contribution(s)
 *       with the Work to which such Contribution(s) was submitted. If You
 *       institute patent litigation against any entity (including a
 *       cross-claim or counterclaim in a lawsuit) alleging that the Work
 *       or a Contribution incorporated within the Work constitutes direct
 *       or contributory patent infringement, then any patent licenses
 *       granted to You under this License for that Work shall terminate
 *       as of the date such litigation is filed.
 *
 *    4. Redistribution. You may reproduce and distribute copies of the
 *       Work or Derivative Works thereof in any medium, with or without
 *       modifications, and in Source or Object form, provided that You
 *       meet the following conditions:
 *
 *       (a) You must give any other recipients of the Work or
 *           Derivative Works a copy of this License; and
 *
 *       (b) You must cause any modified files to carry prominent notices
 *           stating that You changed the files; and
 *
 *       (c) You must retain, in the Source form of any Derivative Works
 *           that You distribute, all copyright, patent, trademark, and
 *           attribution notices from the Source form of the Work,
 *           excluding those notices that do not pertain to any part of
 *           the Derivative Works; and
 *
 *       (d) If the Work includes a "NOTICE" text file as part of its
 *           distribution, then any Derivative Works that You distribute must
 *           include a readable copy of the attribution notices contained
 *           within such NOTICE file, excluding those notices that do not
 *           pertain to any part of the Derivative Works, in at least one
 *           of the following places: within a NOTICE text file distributed
 *           as part of the Derivative Works; within the Source form or
 *           documentation, if provided along with the Derivative Works; or,
 *           within a display generated by the Derivative Works, if and
 *           wherever such third-party notices normally appear. The contents
 *           of the NOTICE file are for informational purposes only and
 *           do not modify the License. You may add Your own attribution
 *           notices within Derivative Works that You distribute, alongside
 *           or as an addendum to the NOTICE text from the Work, provided
 *           that such additional attribution notices cannot be construed
 *           as modifying the License.
 *
 *       You may add Your own copyright statement to Your modifications and
 *       may provide additional or different license terms and conditions
 *       for use, reproduction, or distribution of Your modifications, or
 *       for any such Derivative Works as a whole, provided Your use,
 *       reproduction, and distribution of the Work otherwise complies with
 *       the conditions stated in this License.
 *
 *    5. Submission of Contributions. Unless You explicitly state otherwise,
 *       any Contribution intentionally submitted for inclusion in the Work
 *       by You to the Licensor shall be under the terms and conditions of
 *       this License, without any additional terms or conditions.
 *       Notwithstanding the above, nothing herein shall supersede or modify
 *       the terms of any separate license agreement you may have executed
 *       with Licensor regarding such Contributions.
 *
 *    6. Trademarks. This License does not grant permission to use the trade
 *       names, trademarks, service marks, or product names of the Licensor,
 *       except as required for reasonable and customary use in describing the
 *       origin of the Work and reproducing the content of the NOTICE file.
 *
 *    7. Disclaimer of Warranty. Unless required by applicable law or
 *       agreed to in writing, Licensor provides the Work (and each
 *       Contributor provides its Contributions) on an "AS IS" BASIS,
 *       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 *       implied, including, without limitation, any warranties or conditions
 *       of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
 *       PARTICULAR PURPOSE. You are solely responsible for determining the
 *       appropriateness of using or redistributing the Work and assume any
 *       risks associated with Your exercise of permissions under this License.
 *
 *    8. Limitation of Liability. In no event and under no legal theory,
 *       whether in tort (including negligence), contract, or otherwise,
 *       unless required by applicable law (such as deliberate and grossly
 *       negligent acts) or agreed to in writing, shall any Contributor be
 *       liable to You for damages, including any direct, indirect, special,
 *       incidental, or consequential damages of any character arising as a
 *       result of this License or out of the use or inability to use the
 *       Work (including but not limited to damages for loss of goodwill,
 *       work stoppage, computer failure or malfunction, or any and all
 *       other commercial damages or losses), even if such Contributor
 *       has been advised of the possibility of such damages.
 *
 *    9. Accepting Warranty or Additional Liability. While redistributing
 *       the Work or Derivative Works thereof, You may choose to offer,
 *       and charge a fee for, acceptance of support, warranty, indemnity,
 *       or other liability obligations and/or rights consistent with this
 *       License. However, in accepting such obligations, You may act only
 *       on Your own behalf and on Your sole responsibility, not on behalf
 *       of any other Contributor, and only if You agree to indemnify,
 *       defend, and hold each Contributor harmless for any liability
 *       incurred by, or claims asserted against, such Contributor by reason
 *       of your accepting any such warranty or additional liability.
 *
 *    END OF TERMS AND CONDITIONS
 *
 *    APPENDIX: How to apply the Apache License to your work.
 *
 *       To apply the Apache License to your work, attach the following
 *       boilerplate notice, with the fields enclosed by brackets "{}"
 *       replaced with your own identifying information. (Don't include
 *       the brackets!)  The text should be enclosed in the appropriate
 *       comment syntax for the file format. We also recommend that a
 *       file or class name and description of purpose be included on the
 *       same "printed page" as the copyright notice for easier
 *       identification within third-party archives.
 *
 *    Copyright 2014 Edgar Espina
 *
 *    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 org.jooby.test;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.reflect.Reflection;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.name.Names;
import org.jooby.Deferred;
import org.jooby.Err;
import org.jooby.Jooby;
import org.jooby.MediaType;
import org.jooby.Request;
import org.jooby.Response;
import org.jooby.Result;
import org.jooby.Results;
import org.jooby.Route;
import org.jooby.Route.After;
import org.jooby.Route.Definition;
import org.jooby.Route.Filter;
import org.jooby.Status;
import org.jooby.funzy.Try;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;

/**
 * <h1>tests</h1>
 * <p>
 * In this section we are going to see how to run unit and integration tests in Jooby.
 * </p>
 *
 * <h2>unit tests</h2>
 * <p>
 * We do offer two programming models:
 * </p>
 * <ul>
 * <li>script programming model; and</li>
 * <li>mvc programming model</li>
 * </ul>
 *
 * <p>
 * You don't need much for <code>MVC</code> routes, because a route got binded to a method of some
 * class. So it is usually very easy and simple to mock and run unit tests against a
 * <code>MVC</code> route.
 * </p>
 *
 * <p>
 * We can't say the same for <code>script</code> routes, because a route is represented by a
 * <code>lambda</code> and there is no easy or simple way to get access to the lambda object.
 * </p>
 *
 * <p>
 * We do provide a {@link MockRouter} which simplify unit tests for <code>script routes</code>:
 * </p>
 *
 * <h3>usage</h3>
 *
 * <pre>{@code
 * public class MyApp extends Jooby {
 *   {
 *     get("/test", () -> "Hello unit tests!");
 *   }
 * }
 * }</pre>
 *
 * <p>
 * A unit test for this route, looks like:
 * </p>
 *
 * <pre>
 * &#64;Test
 * public void simpleTest() {
 *   String result = new MockRouter(new MyApp())
 *      .get("/test");
 *   assertEquals("Hello unit tests!", result);
 * }</pre>
 *
 * <p>
 * Just create a new instance of {@link MockRouter} with your application and call one of the HTTP
 * method, like <code>get</code>, <code>post</code>, etc...
 * </p>
 *
 * <h3>mocks</h3>
 * <p>
 * You're free to choose the mock library of your choice. Here is an example using
 * <a href="http://easymock.org">EasyMock</a>:
 * </p>
 *
 * <pre>{@code
 * {
 *   get("/mock", req -> {
 *     return req.path();
 *   });
 * }
 * }</pre>
 *
 * <p>
 * A test with <a href="http://easymock.org">EasyMock</a> looks like:
 * </p>
 * <pre>
 *
 * &#64;Test
 * public void shouldGetRequestPath() {
 *   Request req = EasyMock.createMock(Request.class);
 *   expect(req.path()).andReturn("/mypath");
 *
 *   EasyMock.replay(req);
 *
 *   String result = new MockRouter(new MyApp(), req)
 *      .get("/mock");
 *
 *   assertEquals("/mypath", result);
 *
 *   EasyMock.verify(req);
 * }
 * </pre>
 *
 * <p>
 * You can mock a {@link Response} object in the same way:
 * </p>
 *
 * <pre>{@code
 * {
 *   get("/mock", (req, rsp) -> {
 *     rsp.send("OK");
 *   });
 * }
 * }</pre>
 *
 * <p>
 * A test with <a href="http://easymock.org">EasyMock</a> looks like:
 * </p>
 * <pre>
 *
 * &#64;Test
 * public void shouldUseResponseSend() {
 *   Request req = EasyMock.createMock(Request.class);
 *   Response rsp = EasyMock.createMock(Response.class);
 *   rsp.send("OK");
 *
 *   EasyMock.replay(req, rsp);
 *
 *   String result = new MockRouter(new MyApp(), req, rsp)
 *      .get("/mock");
 *
 *   assertEquals("OK", result);
 *
 *   EasyMock.verify(req, rsp);
 * }
 * </pre>
 *
 * <p>
 * What about external dependencies? It works in a similar way:
 * </p>
 *
 * <pre>{@code
 * {
 *   get("/", () -> {
 *     HelloService service = require(HelloService.class);
 *     return service.salute();
 *   });
 * }
 * }</pre>
 *
 * <pre>
 * &#64;Test
 * public void shouldMockExternalDependencies() {
 *   HelloService service = EasyMock.createMock(HelloService.class);
 *   expect(service.salute()).andReturn("Hola!");
 *
 *   EasyMock.replay(service);
 *
 *   String result = new MockRouter(new MyApp())
 *      .set(service)
 *      .get("/");
 *
 *   assertEquals("Hola!", result);
 *
 *   EasyMock.verify(service);
 * }
 * </pre>
 *
 * <p>
 * The {@link #set(Object)} call push and register an external dependency (usually a mock). This
 * make it possible to resolve services from <code>require</code> calls.
 * </p>
 *
 * <h3>deferred</h3>
 * <p>
 * Mock of promises are possible too:
 * </p>
 *
 * <pre>{@code
 * {
 *   get("/", promise(deferred -> {
 *     deferred.resolve("OK");
 *   }));
 * }
 * }</pre>
 *
 * <pre>
 * &#64;Test
 * public void shouldMockPromises() {
 *
 *   String result = new MockRouter(new MyApp())
 *      .get("/");
 *
 *   assertEquals("OK", result);
 * }
 * </pre>
 *
 * Previous test works for deferred routes:
 *
 * <pre>{@code
 * {
 *   get("/", deferred(() -> {
 *     return "OK";
 *   }));
 * }
 * }</pre>
 *
 * @author edgar
 */
public class MockRouter {

  private static final Route.Chain NOOP_CHAIN = new Route.Chain() {

    @Override
    public List<Route> routes() {
      return ImmutableList.of();
    }

    @Override
    public void next(final String prefix, final Request req, final Response rsp) throws Throwable {
    }
  };

  private static class MockResponse extends Response.Forwarding {

    List<Route.After> afterList = new ArrayList<>();
    private AtomicReference<Object> ref;

    public MockResponse(final Response response, final AtomicReference<Object> ref) {
      super(response);
      this.ref = ref;
    }

    @Override
    public void after(final After handler) {
      afterList.add(handler);
    }

    @Override
    public void send(final Object result) throws Throwable {
      rsp.send(result);
      ref.set(result);
    }

    @Override
    public void send(final Result result) throws Throwable {
      rsp.send(result);
      ref.set(result);
    }

  }

  private static final int CLEAN_STACK = 4;

  @SuppressWarnings("rawtypes")
  private Map<Key, Object> registry = new HashMap<>();

  private List<Definition> routes;

  private Request req;

  private Response rsp;

  public MockRouter(final Jooby app) {
    this(app, empty(Request.class), empty(Response.class));
  }

  public MockRouter(final Jooby app, final Request req) {
    this(app, req, empty(Response.class));
  }

  public MockRouter(final Jooby app, final Request req, final Response rsp) {
    this.routes = Jooby.exportRoutes(hackInjector(app));
    this.req = req;
    this.rsp = rsp;
  }

  public MockRouter set(final Object dependency) {
    return set(null, dependency);
  }

  @SuppressWarnings({"unchecked", "rawtypes"})
  public MockRouter set(final String name, final Object object) {
    traverse(object.getClass(), type -> {
      Object key = Optional.ofNullable(name)
          .map(it -> Key.get(type, Names.named(name)))
          .orElseGet(() -> Key.get(type));
      registry.putIfAbsent((Key) key, object);
    });
    return this;
  }

  public <T> T get(final String path) throws Throwable {
    return execute(Route.GET, path);
  }

  public <T> T post(final String path) throws Throwable {
    return execute(Route.POST, path);
  }

  public <T> T put(final String path) throws Throwable {
    return execute(Route.PUT, path);
  }

  public <T> T patch(final String path) throws Throwable {
    return execute(Route.PATCH, path);
  }

  public <T> T delete(final String path) throws Throwable {
    return execute(Route.DELETE, path);
  }

  public <T> T execute(final String method, final String path) throws Throwable {
    return execute(method, path, MediaType.all, MediaType.all);
  }

  @SuppressWarnings("unchecked")
  private <T> T execute(final String method, final String path, final MediaType contentType,
      final MediaType... accept) throws Throwable {
    List<Filter> filters = pipeline(method, path, contentType, Arrays.asList(accept));
    if (filters.isEmpty()) {
      throw new Err(Status.NOT_FOUND, path);
    }
    Iterator<Filter> pipeline = filters.iterator();
    AtomicReference<Object> ref = new AtomicReference<>();
    MockResponse rsp = new MockResponse(this.rsp, ref);
    while (ref.get() == null && pipeline.hasNext()) {
      Filter next = pipeline.next();
      if (next instanceof Route.ZeroArgHandler) {
        ref.set(((Route.ZeroArgHandler) next).handle());
      } else if (next instanceof Route.OneArgHandler) {
        ref.set(((Route.OneArgHandler) next).handle(req));
      } else if (next instanceof Route.Handler) {
        ((Route.Handler) next).handle(req, rsp);
      } else {
        next.handle(req, rsp, NOOP_CHAIN);
      }
    }
    Object lastResult = ref.get();
    // after callbacks:
    if (rsp.afterList.size() > 0) {
      Result result = wrap(lastResult);
      for (int i = rsp.afterList.size() - 1; i >= 0; i--) {
        result = rsp.afterList.get(i).handle(req, rsp, result);
      }
      if (Result.class.isInstance(lastResult)) {
        return (T) result;
      }
      return result.get();
    }

    // deferred results:
    if (lastResult instanceof Deferred) {
      Deferred deferred = ((Deferred) lastResult);
      // execute deferred code:
      deferred.handler(req, (v, x) -> {
      });
      // get result
      lastResult = deferred.get();
      if (Throwable.class.isInstance(lastResult)) {
        throw (Throwable) lastResult;
      }
    }
    return (T) lastResult;
  }

  private Result wrap(final Object value) {
    if (value instanceof Result) {
      return (Result) value;
    }
    return Results.with(value);
  }

  private List<Route.Filter> pipeline(final String method, final String path,
      final MediaType contentType,
      final List<MediaType> accept) {
    List<Route.Filter> routes = new ArrayList<>();
    for (Route.Definition routeDef : this.routes) {
      Optional<Route> route = routeDef.matches(method, path, contentType, accept);
      if (route.isPresent()) {
        routes.add(routeDef.filter());
      }
    }
    return routes;
  }

  private Jooby hackInjector(final Jooby app) {
    Try.run(() -> {
      Field field = Jooby.class.getDeclaredField("injector");
      field.setAccessible(true);
      Injector injector = proxyInjector(getClass().getClassLoader(), registry);
      field.set(app, injector);
      registry.put(Key.get(Injector.class), injector);
    }).throwException();
    return app;
  }

  @SuppressWarnings("rawtypes")
  private static Injector proxyInjector(final ClassLoader loader, final Map<Key, Object> registry) {
    return Reflection.newProxy(Injector.class, (proxy, method, args) -> {
      if (method.getName().equals("getInstance")) {
        Key key = (Key) args[0];
        Object value = registry.get(key);
        if (value == null) {
          Object type = key.getAnnotation() != null ? key : key.getTypeLiteral();
          IllegalStateException iex = new IllegalStateException("Not found: " + type);
          // Skip proxy and some useless lines:
          Try.apply(() -> {
            StackTraceElement[] stacktrace = iex.getStackTrace();
            return Lists.newArrayList(stacktrace).subList(CLEAN_STACK, stacktrace.length);
          }).onSuccess(stacktrace -> iex
              .setStackTrace(stacktrace.toArray(new StackTraceElement[stacktrace.size()])));
          throw iex;
        }
        return value;
      }
      throw new UnsupportedOperationException(method.toString());
    });
  }

  @SuppressWarnings("rawtypes")
  private void traverse(final Class type, final Consumer<Class> set) {
    if (type != Object.class) {
      set.accept(type);
      Optional.ofNullable(type.getSuperclass()).ifPresent(it -> traverse(it, set));
      Arrays.asList(type.getInterfaces()).forEach(it -> traverse(it, set));
    }
  }

  private static <T> T empty(final Class<T> type) {
    return Reflection.newProxy(type, (proxy, method, args) -> {
      throw new UnsupportedOperationException(method.toString());
    });
  }

}
