/**
 *                                  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.apitool;

import org.jooby.Jooby;
import org.jooby.MediaType;
import org.jooby.Route;
import org.jooby.internal.apitool.BytecodeRouteParser;

import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.OptionalInt;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * Parse and extract route metadata from bytecode and documentation from source code.
 *
 * @author edgar
 * @since 1.2.0
 */
public class ApiParser {

  private static final Predicate<RouteMethod> TRUE = r -> true;

  private final Path dir;
  private final Map<Predicate<RouteMethod>, Consumer<RouteMethod>> customizer = new LinkedHashMap<>();
  private final Predicate<RouteMethod> filter;
  private ClassLoader loader = getClass().getClassLoader();

  /**
   * Creates a new {@link ApiParser}.
   *
   * @param dir Source code directory. Required for javadoc parser.
   * @param filter Route method filter.
   */
  public ApiParser(Path dir, Predicate<RouteMethod> filter) {
    this.dir = dir;
    this.filter = filter;
  }

  /**
   * Creates a new {@link ApiParser}.
   *
   * @param dir Source code directory. Required for javadoc parser.
   */
  public ApiParser(Path dir) {
    this(dir, TRUE);
  }

  /**
   * Parse application bytecode, build route methods from it and merge output with the given routes.
   *
   * @param application Application to parse.
   * @return List of route methods.
   * @throws Exception If something goes wrong.
   */
  public List<RouteMethod> parseFully(Jooby application) throws Exception {
    List<RouteMethod> methods = parseFully(application.getClass().getName(),
        Jooby.exportRoutes(application));

    return methods;
  }

  /**
   * Parse application bytecode, build route methods from it and export all metadata to <code>.json</code>.
   *
   * @param outputBaseDir Output base directory. This method appends the java package of the given
   *     application.
   * @param application Application to parse.
   * @return List of route methods.
   * @throws Exception If something goes wrong.
   */
  public Path export(Path outputBaseDir, String application) throws Exception {
    return new BytecodeRouteParser(loader, dir).export(outputBaseDir, application);
  }

  /**
   * Parse application bytecode and build route methods from it.
   *
   * @param application Application to parse.
   * @return List of route methods.
   * @throws Exception If something goes wrong.
   */
  public List<RouteMethod> parse(String application) throws Exception {
    return new BytecodeRouteParser(loader, dir).parse(application).stream()
        .filter(filter)
        .collect(Collectors.toList());
  }

  /**
   * Parse application bytecode, build route methods from it and merge output with the given routes.
   *
   * @param application Application to parse.
   * @param routes Application routes.
   * @return List of route methods.
   * @throws Exception If something goes wrong.
   */
  public List<RouteMethod> parseFully(String application, List<Route.Definition> routes)
      throws Exception {
    List<RouteMethod> methods = parse(application);

    BiFunction<String, String, OptionalInt> routeIndex = (verb, pattern) -> {
      RouteMethod it = new RouteMethod(verb, pattern, new RouteResponse(void.class));
      return IntStream.range(0, methods.size())
          .filter(i -> methods.get(i).equals(it))
          .findFirst();
    };

    List<RouteMethod> result = new ArrayList<>(routes.size());
    for (Route.Definition route : routes) {
      routeIndex.apply(route.method(), route.pattern())
          .ifPresent(i -> result.add(complement(route, methods.remove(i))));
    }

    customizer.entrySet().forEach(it ->
        result.stream()
            .filter(it.getKey())
            .forEach(it.getValue())
    );

    return result;
  }

  /**
   * Set a class loader to use.
   *
   * @param loader Class loader.
   * @return This parser.
   */
  public ApiParser with(ClassLoader loader) {
    this.loader = Objects.requireNonNull(loader, "ClassLoader required.");
    return this;
  }

  /**
   * Modify one or more route method who matches the filter. Work as a API to fix possible missing
   * metadata.
   *
   * @param matcher Route matcher.
   * @param customizer Customizer.
   * @return This parser.
   */
  public ApiParser modify(final Predicate<RouteMethod> matcher,
      final Consumer<RouteMethod> customizer) {
    this.customizer.put(matcher, customizer);
    return this;
  }

  private RouteMethod complement(Route.Definition route, final RouteMethod method) {
    method.attributes(route.attributes());
    String name = route.name();
    if (!name.equals("/anonymous")) {
      method.name(name);
    }

    BiConsumer<List<MediaType>, Consumer<List<String>>> types = (values, setter) ->
        setter.accept(values.stream()
            .map(MediaType::name)
            .filter(it -> !it.equals("*/*"))
            .collect(Collectors.toList()));

    types.accept(route.consumes(), method::consumes);
    types.accept(route.produces(), method::produces);

    return method;
  }
}


/**
 *                                  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.scanner;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.Service;
import com.google.common.util.concurrent.ServiceManager;
import com.google.inject.Binder;
import com.google.inject.Module;
import com.typesafe.config.Config;
import io.github.classgraph.ClassGraph;
import io.github.classgraph.ClassInfo;
import io.github.classgraph.ScanResult;
import org.jooby.Env;
import org.jooby.Jooby;
import org.jooby.Router;
import org.jooby.funzy.Throwing;

import static org.jooby.funzy.Throwing.throwingSupplier;

import org.jooby.mvc.Path;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Named;
import javax.inject.Provider;
import javax.inject.Singleton;
import java.lang.reflect.Modifier;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 *
scanner

 *

 * Classpath scanning services via
 * FastClasspathScanner.
 * FastClasspathScanner is an uber-fast, ultra-lightweight classpath scanner for Java, Scala and
 * other JVM languages.
 *

 *
 *
usage

 *
 *
{@code
 * {
 *   use(new Scanner());
 * }
 * }

 *
 *

 * This modules scan the application class-path and automatically discover and register
 * MVC routes/controllers and {@link Jooby} applications.
 *

 *
 *

 * It scans the application package. That's the package where your bootstrap application belong to.
 * Multi-package scanning is available too:
 *

 *
 *
{@code
 * {
 *   use(new Scanner("foo", "bar"));
 * }
 * }

 *
 *
services

 *
 *

 * The next example scans and initialize any class in the application package annotated with
 * Named:
 *

 *
 *
{@code
 * {
 *   use(new Scanner()
 *     .scan(Named.class)
 *   );
 * }
 * }

 *
 *

 * The next example scans and initialize any class in the application package that implements
 * MyService:
 *

 *
 *
{@code
 * {
 *   use(new Scanner()
 *     .scan(MyService.class)
 *   );
 * }
 * }

 *
 *

 * Guava {@link Service} are also supported:
 *

 *
 *
{@code
 * {
 *   use(new Scanner()
 *     .scan(com.google.common.util.concurrent.Service.class)
 *   );
 *
 *   get("/guava", req -> {
 *     ServiceManager sm = req.require(ServiceManager.class);
 *     ...
 *   });
 * }
 * }

 *
 *

 * They are added to {@link ServiceManager} and started and stopped automatically.
 *

 *
 *

 * Raw/plain Guice {@link Module} are supported too
 *

 * :
 *
 *
{@code
 * {
 *   use(new Scanner()
 *     .scan(Module.class)
 *   );
 * }
 * }

 *
 *

 * Of course, you can combine two or more strategies:
 *

 *
 *
{@code
 * {
 *   use(new Scanner()
 *     .scan(MyService.class)
 *     .scan(Named.class)
 *     .scan(Singleton.class)
 *     .scan(MyAnnotation.class)
 *   );
 * }
 * }

 *
 *

 * In all cases, services are created as singleton and started/stopped automatically
 * when {@link PostConstruct} and {@link PreDestroy} annotations are present.
 *

 *
 * @author edgar
 * @since 1.0.0
 */
public class Scanner implements Jooby.Module {

  @SuppressWarnings("rawtypes")
  private static final Predicate<Class> A = Class::isAnnotation;

  @SuppressWarnings("rawtypes")
  private static final Predicate<Class> C = k -> !Modifier.isAbstract(k.getModifiers());

  @SuppressWarnings("rawtypes")
  private static final Predicate<Class> I = A.negate().and(Class::isInterface);

  @SuppressWarnings("rawtypes")
  private static final Predicate<Class> S = I.or(A).negate();

  private List<String> packages;

  @SuppressWarnings("rawtypes")
  private final Set<Class> serviceTypes = new LinkedHashSet<>();

  /**
   * Creates a new {@link Scanner} and uses the provided scan spec or packages.
   *
   * @param scanSpec Scan spec or packages. See Scan
   *        spec.
   */
  public Scanner(final String... scanSpec) {
    this.packages = Lists.newArrayList(scanSpec);
  }

  /**
   * Creates a new {@link Scanner} and use the application package (a.k.a as namespace).
   */
  public Scanner() {
  }

  @SuppressWarnings({"unchecked", "rawtypes"})
  @Override
  public void configure(final Env env, final Config conf, final Binder binder) {
    List<String> packages = Optional.ofNullable(this.packages)
        .orElseGet(() -> ImmutableList.of(conf.getString("application.ns")));
    Set<String> spec = Sets.newLinkedHashSet(packages);
    serviceTypes.forEach(it -> spec.add(it.getPackage().getName()));

    ClassGraph scanner = new ClassGraph().enableAllInfo()
        .whitelistPackages(spec.toArray(new String[spec.size()]));

    Router routes = env.router();

    ClassLoader loader = getClass().getClassLoader();
    Throwing.Function<String, Class> loadClass = loader::loadClass;

    // bind once as singleton + post/pre callbacks
    Set<Object> bindings = new HashSet<>();
    Predicate<Object> once = bindings::add;

    Consumer<Class> bind = klass -> {
      binder.bind(klass).asEagerSingleton();
      env.lifeCycle(klass);
    };

    ScanResult result = scanner.scan();

    Predicate<ClassInfo> inPackage = c -> packages.stream()
        .anyMatch(c.getName()::startsWith);

    /** Controllers: */
    result.getClassesWithAnnotation(Path.class.getName())
        .stream()
        .filter(once)
        .map(ClassInfo::getName)
        .map(loadClass)
        .filter(C)
        .forEach(routes::use);

    String mainClass = conf.getString("application.class");
    /** Apps: */
    result.getSubclasses(Jooby.class.getName())
        .stream()
        .filter(once)
        .map(ClassInfo::getName)
        .filter(name -> !name.equals(mainClass))
        .map(loadClass)
        .filter(C)
        .forEach(klass -> routes.use(((Jooby) newObject(klass))));

    /** Annotated with: */
    serviceTypes.stream()
        .filter(A)
        .forEach(a -> result.getClassesWithAnnotation(a.getName())
            .stream()
            .filter(once)
            .map(ClassInfo::getName)
            .map(loadClass)
            .filter(C)
            .forEach(bind));

    /** Implements: */
    serviceTypes.stream()
        .filter(I)
        .filter(type -> type != Jooby.Module.class && type != Module.class && type != Service.class)
        .forEach(i -> result.getClassesImplementing(i.getName())
            .stream()
            .filter(inPackage)
            .filter(once)
            .map(ClassInfo::getName)
            .map(loadClass)
            .filter(C)
            .forEach(bind));

    /** SubclassOf: */
    serviceTypes.stream()
        .filter(S)
        .forEach(k -> result.getSubclasses(k.getName())
            .stream()
            .filter(inPackage)
            .filter(once)
            .map(ClassInfo::getName)
            .map(loadClass)
            .filter(C)
            .forEach(bind));

    /** Guice modules: */
    if (serviceTypes.contains(Module.class)) {
      result.getClassesImplementing(Module.class.getName())
          .stream()
          .filter(inPackage)
          .filter(once)
          .map(ClassInfo::getName)
          .map(loadClass)
          .filter(C)
          .forEach(klass -> ((Module) newObject(klass)).configure(binder));
    }

    /** Guava services: */
    if (serviceTypes.contains(Service.class)) {
      Set<Class<Service>> guavaServices = new HashSet<>();
      result.getClassesImplementing(Service.class.getName())
          .stream()
          .filter(inPackage)
          .filter(once)
          .map(ClassInfo::getName)
          .map(loadClass)
          .filter(C)
          .forEach(guavaServices::add);

      if (guavaServices.size() > 0) {
        guavaServices(env, binder, guavaServices);
      }
    }
  }

  /**
   * Add a scan criteria like an annotation, interface or class.
   *
   * @param type A scan criteria/type.
   * @return This module.
   */
  public Scanner scan(final Class<?> type) {
    // standard vs guice annotations
    if (type == Named.class || type == com.google.inject.name.Named.class) {
      serviceTypes.add(Named.class);
      serviceTypes.add(com.google.inject.name.Named.class);
    } else if (type == Singleton.class || type == com.google.inject.Singleton.class) {
      serviceTypes.add(Singleton.class);
      serviceTypes.add(com.google.inject.Singleton.class);
    } else {
      serviceTypes.add(type);
    }
    return this;
  }

  private static <T> T newObject(final Class<T> klass) {
    return throwingSupplier(klass::newInstance).get();
  }

  @SuppressWarnings({"unchecked", "rawtypes"})
  private static void guavaServices(final Env env, final Binder binder,
      final Set<Class<Service>> serviceTypes) {
    Consumer<Class> guavaService = klass -> {
      binder.bind(klass).asEagerSingleton();
      serviceTypes.add(klass);
    };

    serviceTypes.forEach(guavaService);
    // lazy service manager
    AtomicReference<ServiceManager> sm = new AtomicReference<>();
    Provider<ServiceManager> smProvider = sm::get;
    binder.bind(ServiceManager.class).toProvider(smProvider);
    // ask Guice for services, create ServiceManager and start services
    env.onStart(r -> {
      List<Service> services = serviceTypes.stream()
          .map(r::require)
          .collect(Collectors.toList());
      sm.set(new ServiceManager(services));
      sm.get().startAsync().awaitHealthy();
    });
    // stop services
    env.onStop(() -> sm.get().stopAsync().awaitStopped());
  }

  @SuppressWarnings({"unchecked", "rawtypes"})
  private static Predicate<Class> type(final Class type) {
    return klass -> klass.isAssignableFrom(type);
  }

}


/**
 * 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.apitool;

import com.google.common.io.ByteStreams;
import com.google.inject.Binder;
import com.google.inject.TypeLiteral;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import io.swagger.models.Swagger;
import io.swagger.parser.SwaggerParser;
import io.swagger.util.Json;
import io.swagger.util.Yaml;
import org.jooby.Env;
import org.jooby.Jooby;
import org.jooby.MediaType;
import org.jooby.Results;
import org.jooby.Route;
import org.jooby.Router;
import org.jooby.apitool.raml.Raml;
import org.jooby.funzy.Throwing;
import org.jooby.internal.apitool.SwaggerBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;

/**
 *
API tool

 *

 * Automatically export your HTTP API to open standards like
 * Swagger and RAML.
 *

 *

 * This module generates live documentation from your HTTP API.
 *

 *
 *
usage

 *
 *
{@code
 * {
 *    use(new ApiTool()
 *      .swagger("/swagger")
 *      .raml("/raml")
 *    );
 * }
 * }

 *
 *

 * Those lines export your API to Swagger and
 * RAML.
 *

 *
 *
example

 *
Suppose you have a Pet API like:

 *
 *

 * {
 *   /**
 *     * Everything about your Pets.
 *     */
 *   path("/api/pets", () {@literal ->} {
 *     /**
 *       * List pets ordered by name.
 *       *
 *       * @param start Start offset, useful for paging. Default is 0.
 *       * @param max Max page size, useful for paging. Default is 200.
 *       * @return Pets ordered by name.
 *       */
 *      get(req {@literal ->} {
 *        int start = req.param("start").intValue(0);
 *        int max = req.param("max").intValue(200);
 *        DB db = req.require(DB.class);
 *        List<Pet> pets = db.findAll(Pet.class, start, max);
 *        return pets;
 *      });
 *     /**
 *       * Find pet by ID
 *       *
 *       * @param id Pet ID.
 *       * @return Returns 200 with a single pet or 404
 *       */
 *       get("/:id",req {@literal ->} {
 *         int id = req.param("id").intValue();
 *         DB db = req.require(DB.class);
 *         Pet pet = db.find(Pet.class,id);
 *         return pet;
 *       });
 *     /**
 *       * Add a new pet to the store.
 *       *
 *       * @param body Pet object that needs to be added to the store.
 *       * @return Returns a saved pet.
 *       */
 *       post(req {@literal ->} {
 *         Pet pet = req.body().to(Pet.class);
 *         DB db = req.require(DB.class);
 *         db.save(pet);
 *         return pet;
 *       });
 *     /**
 *       * Update an existing pet.
 *       *
 *       * @param body Pet object that needs to be updated.
 *       * @return Returns a saved pet.
 *       */
 *       put(req {@literal ->} {
 *         Pet pet = req.body().to(Pet.class);
 *         DB db = req.require(DB.class);db.save(pet);
 *         return pet;
 *       });
 *     /**
 *       * Deletes a pet by ID.
 *       *
 *       * @param id Pet ID.
 *       * @return A 204
 *       */
 *       delete("/:id",req {@literal ->} {
 *         int id = req.param("id").intValue();
 *         DB db = req.require(DB.class);
 *         db.delete(Pet.class,id);
 *         return Results.noContent();
 *       });
 *    });
 *
 *    /**
 *     * Install API Doc and export your HTTP API:
 *     */
 *    use(new ApiTool()
 *      .swagger("/swagger")
 *      .raml("/raml")
 *    );
 *
 * }
 *

 *
 *

 * The ApiTool module automatically exports your application to
 * Swagger and RAML.
 *

 *
 *

 * Works for MVC routes and Kotlin.
 *

 *
 *
keep documentation

 *

 * The {@link ApiTool} module parse documentation from source code. It works well as long as the
 * source code is present, but it won't work after you deploy your application.
 *

 *

 * To fix this we provide a Maven and
 * Gradle tasks that process your API at build time and keep the
 * documentation available for later usage.
 *

 *
 *
maven plugin

 *
Go to the plugins section of your pom.xml and add these lines:

 *
{@code
 * <plugin>
 *   <groupId>org.jooby</groupId>
 *   <artifactId>jooby-maven-plugin</artifactId>
 *   <executions>
 *     <execution>
 *       <goals>
 *         <goal>apitool</goal>
 *       </goals>
 *     </execution>
 *   </executions>
 * </plugin>
 * }
 *

 *

 * Now, compile your application the apitool plugin will generates a
 * .json file for your API.
 *

 *
 *
gradle task

 *

 * Go to build.gradle and add these lines:
 *

 *
 *
{@code
 * buildscript {
 *     dependencies {
 *         classpath group: 'org.jooby', name: 'jooby-gradle-plugin', version: '1.1.3'
 *     }
 * }
 *
 * apply plugin: 'jooby'
 * }

 *
 *
Then run:

 *
 *

 *   joobyApiTool
 *

 *
 *
options

 *

 * There are a couple of options that control what is exposed as well as how do we export.
 *

 *
 *
filter

 *

 * The filter option controls what routes are exported.
 *

 *
{@code
 *  {
 *
 *    use(new ApiTool()
 *        // Keep /api/* routes:
 *       .filter(route -> route.pattern().startWiths("/api/")
 *    );
 *  }
 * }

 *
 *
disable try it

 *

 * Disable the tryIt button in Swagger or RAML.
 *

 *
 *
{@code
 *  {
 *    use(new ApiTool()
 *       .disableTryIt()
 *    );
 *  }
 * }

 *
 *
disable UI

 *

 * Disable UI for Swagger or RAML.
 *

 *
 *
{@code
 *  {
 *    use(new ApiTool()
 *       .disableUI()
 *    );
 *  }
 * }

 *
 *
theme

 *

 * Set the default theme for Swagger or RAML.
 *

 *
 *
{@code
 *  {
 *    use(new ApiTool()
 *       .raml(
 *          new Options("/raml")
 *            .theme("dark")
 *       )
 *       .swagger(
 *          new Options("/swagger")
 *            .theme("muted")
 *       )
 *    );
 *  }
 * }

 *
 *

 * Themes can set at runtime too via theme query parameter:
 *

 *
 *

 *   /swagger?theme=material
 *
 *   /raml?theme=dark
 *

 *

 * Complete list of Swagger theme are available here.
 *

 *

 * Raml comes with only two themes: light and dark.
 *

 *
 *
advanced usage

 *

 * Sometimes the {@link ApiTool} module doesn't generate correct metadata like type, names,
 * documentation, etc. When that happens you need to manually fix/provide metadata.
 *

 *
 *
{@code
 *   {
 *     use(new ApiTool()
 *       .modify(r -> r.pattern().equals("/api/pet/{id}", route -> {
 *         // Fix java doc for id parameter
 *         route.param("id", param -> {
 *           param.description("Fixing doc for ID");
 *         });
 *
 *         // Set response type
 *         route.response()
 *           .type(Pet.class);
 *       });
 *     );
 *   }
 * }
 *

 *
 *

 * It is possible to customize Swagger/RAML objects:
 *

 *
 *
{@code
 *   {
 *     use(new ApiTool()
 *       .swagger(swagger -> {
 *         // Modify swagger resources.
 *         ...
 *       })
 *       .raml(raml -> {
 *         // Modify raml resources.
 *         ...
 *       });
 *     );
 *   }
 * }
 *

 *
 *

 * This option is required when you want to customize/complement Swagger/RAML objects.
 *

 *
 * @since 1.2.0
 */
public class ApiTool implements Jooby.Module {

  /**
   * Export options. Control whenever turn off UI, try button or default theme.
   */
  public static class Options {
    boolean showUI = true;

    boolean tryIt = true;

    String path;

    String theme;

    String file;

    Function<RouteMethod, String> tagger = DEFAULT_TAGGER;

    String redoc;

    private Options() {
    }

    private Options(String path, Options defaults) {
      this(path);
      showUI = defaults.showUI;
      tryIt = defaults.tryIt;
      theme = defaults.theme;
    }

    /**
     * Creates a new {@link Options} object.
     *
     * @param path Path to mount the export tool. Usually /swagger or /raml.
     */
    public Options(String path) {
      this.path = Route.normalize(Objects.requireNonNull(path, "Path required."));
    }

    /**
     * Turn off UI.
     *
     * @return This option.
     */
    public Options disableUI() {
      this.showUI = false;
      return this;
    }

    /**
     * Disable try button.
     *
     * @return This option.
     */
    public Options disableTryIt() {
      this.tryIt = false;
      return this;
    }

    /**
     * Set default theme.
     *
     *

     * Complete list of Swagger theme are available here.
     *

     *

     * Raml comes with only two themes: light and dark.
     *

     *
     * @param theme Theme name.
     * @return This options.
     */
    public Options theme(String theme) {
      this.theme = Objects.requireNonNull(theme, "Theme required.");
      return this;
    }

    /**
     * Set specification file like swagger.json, api.raml, etc...
     * If this file is present the ApiTool module uses it (no source scan occurs).
     *
     *
{@code
     *
     *   use(new ApiTool()
     *     .swagger(options -> {
     *       options.use("my-swagger.json");
     *     });
     *   );
     *
     * }

     *
     * @param file Classpath file location.
     * @return This options.
     */
    public Options use(String file) {
      Objects.requireNonNull(file, "File location required.");
      if (file.startsWith("/")) {
        this.file = file;
      } else {
        this.file = "/" + file;
      }
      return this;
    }

    /**
     * Set specification file like swagger.json, api.raml, etc...
     * If this file is present the ApiTool module uses it (no source scan occurs).
     *
     *
{@code
     *
     *   use(new ApiTool()
     *     .swagger(options -> {
     *       options.use("my-swagger.json");
     *     });
     *   );
     *
     * }

     *
     * @param file External file location.
     * @return This options.
     */
    public Options use(Path file) {
      this.file = Objects.requireNonNull(file, "File location required.").toString();
      return this;
    }

    /**
     * Set a custom tagger (a.k.a as groupBy operator). This function creates custom Swagger tags
     * (has no effects on RAML).
     *
     * @param tagger Custom tagger.
     * @return This options.
     */
    public Options tagger(Function<RouteMethod, String> tagger) {
      this.tagger = Objects.requireNonNull(tagger, "Swagger tagger required.");
      return this;
    }

    /**
     * Add ReDoc UI to swagger
     * (has no effects on RAML).
     *
     * @param path Redoc base path.
     * @return This options.
     */
    public Options redoc(String path) {
      this.redoc = Route.normalize(path);
      return this;
    }

    /**
     * Add ReDoc UI to swagger
     * (has no effects on RAML).
     *
     * @return This options.
     */
    public Options redoc() {
      return redoc("/redoc");
    }
  }

  static final Function<RouteMethod, String> DEFAULT_TAGGER = r -> {
    Map<String, Object> attributes = r.attributes();
    if (attributes == null) {
      return r.pattern();
    }

    return Stream
        .of(attributes.get("swagger.tag"), attributes.get("route.tag"))
        .filter(Objects::nonNull)
        .findFirst()
        .map(Objects::toString)
        .orElse(r.pattern());
  };

  private static final TypeLiteral<Set<Route.Definition>> M = new TypeLiteral<Set<Route.Definition>>() {
  };

  private static final String REDOC = "<!DOCTYPE html>\n"
      + "\n"
      + "  \n"
      + "    <title>%s</title>\n"
      + "    \n"
      + "    <meta charset=\"utf-8\"/>\n"
      + "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n"
      + "    <link href=\"https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700\" rel=\"stylesheet\">\n"
      + "    \n"
      + "  \n"
      + "  \n"
      + "    <redoc spec-url=\"%s\"></redoc>\n"
      + "    \n"
      + "  \n"
      + "";

  private static final String RAML_STATIC = "/META-INF/resources/webjars/api-console/3.0.17/dist/";

  private static final String SWAGGER_STATIC = "/META-INF/resources/webjars/swagger-ui/3.17.1/";

  private static final String SWAGGER_THEME = "/META-INF/resources/webjars/swagger-ui-themes/3.0.0/themes/3.x/";

  protected Predicate<RouteMethod> filter = r -> true;

  private Options options = new Options();

  private Options swaggerOptions;

  private Consumer<Swagger> swagger;

  private Options ramlOptions;

  private Consumer<Raml> raml;

  private final Map<Predicate<RouteMethod>, Consumer<RouteMethod>> customizer = new LinkedHashMap<>();

  private Path basedir;

  /**
   * Creates a new instance of {@link ApiTool}.
   *
   * @param basedir Base directory to lookup for javadoc.
   */
  public ApiTool(Path basedir) {
    this.basedir = basedir;
  }

  /**
   * Creates a new {@link ApiTool}.
   */
  public ApiTool() {
    this(null);
  }

  @Override public void configure(final Env env, final Config conf, final Binder binder)
      throws Exception {
    boolean useFile = Stream.of(swaggerOptions, ramlOptions)
        .filter(Objects::nonNull)
        .filter(it -> it.file != null)
        .findFirst()
        .isPresent();
    Throwing.Function<Set<Route.Definition>, List<RouteMethod>> provider = null;
    if (!useFile) {
      Path dir = Optional.ofNullable(basedir).orElse(Paths.get(conf.getString("user.dir")));

      ApiParser parser = new ApiParser(dir, filter);
      customizer.forEach(parser::modify);

      provider = routes -> parser
          .parseFully(conf.getString("application.class"), new ArrayList<>(routes));
      if (!env.name().equals("dev")) {
        provider = provider.memoized();
      }

      binder.bind(ApiParser.class).toInstance(parser);
    }

    String contextPath = conf.getString("application.path");
    if (swaggerOptions != null) {
      swagger(contextPath, env.router(), swaggerOptions, conf, swagger, provider);
    }
    if (ramlOptions != null) {
      raml(contextPath, env.router(), ramlOptions, raml, provider);
    }
  }

  @Override public Config config() {
    return ConfigFactory.parseResources(ApiTool.class, "apitool.conf");
  }

  /**
   * Select which route is going to be exported to Swagger/RAML.
   *
   * @param predicate True, if route is exported.
   * @return This tool.
   */
  public ApiTool filter(Predicate<RouteMethod> predicate) {
    this.filter = predicate;
    return this;
  }

  /**
   * Turn off UI for Swagger and Raml.
   *
   * @return This tool.
   */
  public ApiTool disableUI() {
    options.disableUI();
    return this;
  }

  /**
   * Turn off live-testing (try button) for Swagger and Raml.
   *
   * @return This tool.
   */
  public ApiTool disableTryIt() {
    options.disableTryIt();
    return this;
  }

  /**
   * Mount Swagger at /swagger
   *
   * @return This option.
   */
  public ApiTool swagger() {
    return swagger("/swagger");
  }

  /**
   * Mount ReDoc at /redoc
   *
   * @return This option.
   */
  public ApiTool redoc() {
    return redoc("/redoc");
  }

  /**
   * Mount ReDoc at /redoc
   *
   * @param path Redoc path.
   * @return This option.
   */
  public ApiTool redoc(String path) {
    return swagger(new Options("/swagger").disableUI().redoc(path));
  }

  /**
   * Mount Swagger at the given path.
   *
   * @param path Path to mount swagger.
   * @return This tool.
   */
  public ApiTool swagger(String path) {
    return swagger(path, null);
  }

  /**
   * Mount Swagger at /swagger and set a customizer.
   *
   * @param swagger Swagger customizer.
   * @return This tool.
   */
  public ApiTool swagger(Consumer<Swagger> swagger) {
    return swagger("/swagger", swagger);
  }

  /**
   * Mount Swagger at the given path and customize Swagger objects.
   *
   * @param path Path to mount swagger.
   * @param swagger Customizer.
   * @return This tool.
   */
  public ApiTool swagger(String path, Consumer<Swagger> swagger) {
    return swagger(new Options(path, options), swagger);
  }

  /**
   * Mount Swagger using the given options.
   *
   * @param options Swagger options.
   * @return This tool.
   */
  public ApiTool swagger(Options options) {
    return swagger(options, null);
  }

  /**
   * Mount Swagger using the given options.
   *
   * @param options Swagger options.
   * @param swagger Customizer.
   * @return This tool.
   */
  public ApiTool swagger(Options options, Consumer<Swagger> swagger) {
    this.swaggerOptions = Objects.requireNonNull(options, "Options required.");
    this.swagger = swagger;
    return this;
  }

  /**
   * Mount RAML using at /raml.
   *
   * @return This tool.
   */
  public ApiTool raml() {
    return raml("/raml");
  }

  /**
   * Mount RAML at the given path.
   *
   * @param path Path to mount raml.
   * @return This tool.
   */
  public ApiTool raml(String path) {
    return raml(path, null);
  }

  /**
   * Mount RAML at the given path and customize RAML objects.
   *
   * @param path Path to mount raml.
   * @param raml RAML customizer.
   * @return This tool.
   */
  public ApiTool raml(String path, Consumer<Raml> raml) {
    return raml(new Options(path, options), raml);
  }

  /**
   * Mount RAML using the given options.
   *
   * @param options RAML options.
   * @return This tool.
   */
  public ApiTool raml(Options options) {
    return raml(options, null);
  }

  /**
   * Mount RAML using the given options.
   *
   * @param options RAML options.
   * @param raml RAML customizer.
   * @return This tool.
   */
  public ApiTool raml(Options options, Consumer<Raml> raml) {
    this.ramlOptions = Objects.requireNonNull(options, "Options required.");
    this.raml = raml;
    return this;
  }

  /**
   * Modify one or more route method who matches the filter. Work as a API to fix possible missing
   * metadata.
   *
   * @param matcher Route matcher.
   * @param customizer Customizer.
   * @return This tool.
   */
  public ApiTool modify(final Predicate<RouteMethod> matcher,
      final Consumer<RouteMethod> customizer) {
    this.customizer.put(matcher, customizer);
    return this;
  }

  private static void raml(String contextPath, Router router, Options options,
      Consumer<Raml> configurer,
      Throwing.Function<Set<Route.Definition>, List<RouteMethod>> provider) throws IOException {
    String api = options.path + "/api.raml";
    /** /api.raml: */
    if (options.file == null) {
      router.get(api, req -> {
        Config conf = req.require(Config.class);
        Map<String, Object> hash = conf.getConfig("raml").root().unwrapped();
        Raml base = Json.mapper().convertValue(hash, Raml.class);
        Raml raml = Raml.build(base, provider.apply(req.require(M)));
        if (configurer != null) {
          configurer.accept(raml);
        }
        return Results.ok(raml.toYaml()).type("text/yml");
      });
    } else {
      byte[] ramlString = readRaml(options.file);
      router.get(api, req -> {
        return Results.ok(ramlString).type("text/yml");
      });
    }

    if (options.showUI) {
      router.assets(options.path + "/static/**", RAML_STATIC + "{0}");

      String staticPath = Route.normalize(contextPath + options.path);
      String ramlPath = Route.normalize(contextPath + api);
      String index = fileString(RAML_STATIC + "index.html")
          .replace("styles/", staticPath + "/static/styles/")
          .replace("scripts/", staticPath + "/static/scripts/")
          .replace("<raml-initializer></raml-initializer>",
              "<raml-console-loader options=\"{ disableRamlClientGenerator: true, disableThemeSwitcher: true, disableTryIt: "
                  + (!options.tryIt) + " }\" src=\""
                  + ramlPath
                  + "\"></raml-console-loader>");
      /** API console: */
      router.get(options.path, req -> {
        String page = Optional.ofNullable(req.param("theme").value(options.theme))
            .map(theme -> index
                .replace("api-console-light-theme.css", "api-console-" + theme + "-theme.css"))
            .orElse(index);
        return Results.ok(page).type(MediaType.html);
      });
    }
  }

  private static void swagger(String contextPath, Router router, Options options, Config conf,
      Consumer<Swagger> configurer,
      Throwing.Function<Set<Route.Definition>, List<RouteMethod>> provider) throws IOException {
    /** /swagger.json or /swagger.yml: */
    if (options.file == null) {
      router.get(options.path + "/swagger.json", options.path + "/swagger.yml", req -> {
        Map<String, Object> hash = conf.getConfig("swagger").root().unwrapped();
        Swagger base = Json.mapper().convertValue(hash, Swagger.class);
        Swagger swagger = new SwaggerBuilder(options.tagger)
            .build(base, provider.apply(req.require(M)));
        boolean json = req.path().endsWith(".json");
        if (configurer != null) {
          configurer.accept(swagger);
        }
        if (json) {
          return Results.json(Json.mapper().writer().writeValueAsBytes(swagger));
        }
        return Results.ok(Yaml.mapper().writer().writeValueAsBytes(swagger)).type("text/yml");
      });
    } else {
      Swagger swagger = parseSwagger(options.file);
      if (configurer != null) {
        configurer.accept(swagger);
      }
      router.get(options.path + "/swagger.json", options.path + "/swagger.yml", req -> {
        boolean json = req.path().endsWith(".json");
        if (json) {
          return Results.json(Json.mapper().writer().writeValueAsBytes(swagger));
        }
        return Results.ok(Yaml.mapper().writer().writeValueAsBytes(swagger)).type("text/yml");
      });
    }

    String swaggerJsonPath = Route.normalize(contextPath + options.path) + "/swagger.json";

    if (options.showUI) {
      String staticPath = options.path + "/static/";
      router.assets(staticPath + "**", SWAGGER_STATIC + "{0}");
      router.assets(staticPath + "**", SWAGGER_THEME + "{0}");

      String fullStaticPath = Route.normalize(contextPath + staticPath) + "/";
      String index = fileString(SWAGGER_STATIC + "index.html")
          .replace("./", fullStaticPath)
          .replace("https://petstore.swagger.io/v2/swagger.json\",",
              swaggerJsonPath + "\", validatorUrl: null,")
          .replace("",
              options.tryIt ? "" : "");

      router.get(options.path, req -> {
        String page = Optional.ofNullable(req.param("theme").value(options.theme))
            .map(theme -> index.replace("


/**
 *                                  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.couchbase;

import static com.couchbase.client.java.query.dsl.Expression.i;
import static com.couchbase.client.java.query.dsl.Expression.path;
import static com.couchbase.client.java.query.dsl.Expression.s;

import com.couchbase.client.java.query.N1qlQuery;
import com.couchbase.client.java.query.Select;
import com.couchbase.client.java.query.dsl.path.GroupByPath;

/**
 * Utility methods around queries and ID generation.
 *
 * @author edgar
 * @since 1.0.0.CR7
 */
public final class N1Q {

  /** ID separator . */
  private static final String ID_SEP = "::";

  /** Default bucket . */
  static final String COUCHBASE_DEFBUCKET = "couchbase.defbucket";

  /** Meta attribute for storing document type. */
  public static final String CLASS = "_class";

  /**
   * Creates a new {@link N1qlQuery} for the given class, this method build a query like:
   *
   *

   * select b.* from bucket b where b._class = 'model.Beer'
   *

   *
   * @param entityClass Entity class.
   * @return A query.
   */
  public static GroupByPath from(final Class<?> entityClass) {
    return from(System.getProperty(COUCHBASE_DEFBUCKET, "default"), entityClass);
  }

  /**
   * Creates a new {@link N1qlQuery} for the given class, this method build a query like:
   *
   *

   * select b.* from bucket b where b._class = 'model.Beer'
   *

   *
   * @param bucket Bucket name.
   * @param entityClass Entity class.
   * @return A query.
   */
  public static GroupByPath from(final String bucket, final Class<?> entityClass) {
    String alias = String.valueOf(entityClass.getSimpleName().charAt(0));
    return Select.select(alias + ".*")
        .from(i(bucket) + " " + alias)
        .where(path(alias, CLASS).eq(s(entityClass.getName())));
  }

  /**
   * Qualify and ID to construct and unique ID. Given: model.Beer and "ipa" this method returns:
   * model.Beer::ipa.
   *
   * @param entityClass Entity class.
   * @param id Entity id.
   * @return Qualified ID.
   */
  public static String qualifyId(final Class<?> entityClass, final Object id) {
    return qualifyId(entityClass.getName(), id);
  }

  /**
   * Qualify and ID to construct and unique ID. Given: "session" and "ipa" this method returns:
   * session::ipa.
   *
   * @param prefix Prefix class.
   * @param id Object id.
   * @return Qualified ID.
   */
  public static String qualifyId(final String prefix, final Object id) {
    return prefix + ID_SEP + id;
  }
}