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

import com.google.inject.Binder;
import com.google.inject.multibindings.Multibinder;
import com.typesafe.config.Config;
import de.neuland.jade4j.JadeConfiguration;
import de.neuland.jade4j.template.ClasspathTemplateLoader;
import de.neuland.jade4j.template.TemplateLoader;
import static java.util.Objects.requireNonNull;
import org.jooby.Env;
import org.jooby.Jooby;
import org.jooby.Renderer;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

/**
 *
jade

 *

 * jade4j's intention is to be able to process jade
 * templates in Java without the need of a JavaScript environment, while being fully compatible with
 * the original jade syntax.
 *

 *
 *
usage

 *
 *

 * {
 *   use(new Jade());
 *
 *   get("/", req {@literal ->} Results.html("index").put("model", new MyModel());
 *
 *   // or via API
 *   get("/jade-api", req {@literal ->} {
 *     JadeConfiguration jade = req.require(JadeConfiguration.class);
 *     JadeTemplate template = jade.getTemplate("index");
 *     template.renderTemplate(...);
 *   });
 * }
 *

 *
 *

 * Templates are loaded from root of classpath: /.
 *

 *
 *
req locals

 *
 *

 * A template engine has access to ```request locals``` (a.k.a attributes). Here is an example:
 *

 *

 * {
 *   use(new Jade());
 *
 *   get("*", req {@literal ->} {
 *     req.set("req", req);
 *     req.set("session", req.session());
 *   });
 * }
 *

 *
 *

 * By default, there is no access to ```req``` or ```session``` from your template. This example
 * shows how to do it.
 *

 *
 *
template loader

 *

 * Templates are loaded from the root of classpath. Using a custom file extension:
 *

 *
 *

 * {
 *   use(new Jade(".jade"));
 * }
 *

 *
 *

 * Default file extension is: .jade.
 *

 *
 *
template cache

 *

 * Cache is OFF when application.env = dev (useful for template reloading), otherwise
 * is ON and does not expire, unless you explicitly set jade.caching.
 *

 *
 *
pretty print

 *

 * Pretty print is on when application.env = dev , otherwise is off, unless unless you
 * explicitly set jade.prettyprint.
 *

 *
 *

 * That's all folks! Enjoy it!!!
 *

 *
 * @since 1.0.0
 */
public class Jade implements Jooby.Module {

  static class IOTemplateLoader implements TemplateLoader {

    private TemplateLoader loader;

    public IOTemplateLoader(final TemplateLoader loader) {
      this.loader = loader;
    }

    @Override
    public long getLastModified(final String name) throws IOException {
      return loader.getLastModified(name);
    }

    @Override public String getExtension() {
      return loader.getExtension();
    }

    @Override
    public Reader getReader(final String name) throws IOException {
      try {
        return loader.getReader(name);
      } catch (NullPointerException ex) {
        throw new FileNotFoundException(name);
      }
    }

  }

  private BiConsumer<JadeConfiguration, Config> callback;

  private String suffix;

  /**
   * Creates a {@link Jade} instance with a custom suffix.
   *
   * @param suffix A suffix like .html.
   */
  public Jade(final String suffix) {
    this.suffix = requireNonNull(suffix, "Suffix is required.");
  }

  /**
   * Creates a {@link Jade} instance with default suffix .jade.
   */
  public Jade() {
    this(".jade");
  }

  /**
   * Configure callback that let you tweak or modified a {@link JadeConfiguration}.
   *
   * @param callback A callback.
   * @return This module.
   */
  public Jade doWith(final Consumer<JadeConfiguration> callback) {
    requireNonNull(callback, "Configurer callback is required.");
    return doWith((j, c) -> callback.accept(j));
  }

  /**
   * Configure callback that let you tweak or modified a {@link JadeConfiguration}.
   *
   * @param callback A callback.
   * @return This module.
   */
  public Jade doWith(final BiConsumer<JadeConfiguration, Config> callback) {
    this.callback = requireNonNull(callback, "Configurer callback is required.");
    return this;
  }

  @Override
  public void configure(final Env env, final Config conf, final Binder binder) {
    JadeConfiguration jadeconf = new JadeConfiguration();
    boolean dev = env.name().equals("dev");
    boolean caching = conf.hasPath("jade.caching")
        ? conf.getBoolean("jade.caching")
        : !dev;
    boolean prettyPrint = conf.hasPath("jade.prettyprint")
        ? conf.getBoolean("jade.prettyprint")
        : dev;

    jadeconf.setCaching(caching);
    jadeconf.setPrettyPrint(prettyPrint);

    Map<String, Object> sharedVariables = new HashMap<>(2);
    sharedVariables.put("env", env);
    sharedVariables.put("xss", new XssHelper(env));
    jadeconf.setSharedVariables(sharedVariables);

    String ext = suffix.startsWith(".") ? suffix.substring(1) : suffix;
    jadeconf.setTemplateLoader(new ClasspathTemplateLoader("UTF-8", ext));

    if (callback != null) {
      callback.accept(jadeconf, conf);
    }

    // rewrite template loader avoid NPE
    jadeconf.setTemplateLoader(new IOTemplateLoader(jadeconf.getTemplateLoader()));

    binder.bind(JadeConfiguration.class)
        .toInstance(jadeconf);

    Multibinder.newSetBinder(binder, Renderer.class).addBinding()
        .toInstance(new Engine(jadeconf, suffix));
  }

}


/**
 *                                  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.base.Strings;
import com.google.inject.internal.MoreTypes;

import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Metadata and runtime information of a HTTP parameter.
 *
 * @author edgar
 * @since 1.2.0
 */
public class RouteParameter {

  /**
   * Provides visit methods base on parameter kind.
   *
   * @param <T> Result Type.
   */
  public interface Visitor<T> {
    /**
     * Callback method for query HTTP parameters.
     *
     * @param parameter Parameter.
     * @return Computed result.
     */
    T visitQuery(RouteParameter parameter);

    /**
     * Callback method for path HTTP parameters.
     *
     * @param parameter Parameter.
     * @return Computed result.
     */
    T visitPath(RouteParameter parameter);

    /**
     * Callback method for form HTTP parameters.
     *
     * @param parameter Parameter.
     * @return Computed result.
     */
    T visitForm(RouteParameter parameter);

    /**
     * Callback method for body HTTP parameters.
     *
     * @param parameter Parameter.
     * @return Computed result.
     */
    T visitBody(RouteParameter parameter);

    /**
     * Callback method for file upload HTTP parameters.
     *
     * @param parameter Parameter.
     * @return Computed result.
     */
    T visitFile(RouteParameter parameter);

    /**
     * Callback method for header HTTP parameters.
     *
     * @param parameter Parameter.
     * @return Computed result.
     */
    T visitHeader(RouteParameter parameter);
  }

  /**
   * Parameter Kind.
   */
  public enum Kind {

    /** HTTP param inside a query. */
    QUERY {
      @Override public <T> T accept(final RouteParameter parameter, final Visitor<T> visitor) {
        return visitor.visitQuery(parameter);
      }
    },

    /** HTTP param inside a path. */
    PATH {
      @Override public <T> T accept(final RouteParameter parameter, final Visitor<T> visitor) {
        return visitor.visitPath(parameter);
      }
    },

    /** HTTP form param submitted as formurlencoded or multipart. */
    FORM {
      @Override public <T> T accept(final RouteParameter parameter, final Visitor<T> visitor) {
        return visitor.visitForm(parameter);
      }
    },

    /** HTTP body. */
    BODY {
      @Override public <T> T accept(final RouteParameter parameter, final Visitor<T> visitor) {
        return visitor.visitBody(parameter);
      }
    },

    /** File as part of a multipart-upload. */
    FILE {
      @Override public <T> T accept(final RouteParameter parameter, final Visitor<T> visitor) {
        return visitor.visitFile(parameter);
      }
    },

    /** HTTP header .*/
    HEADER {
      @Override public <T> T accept(final RouteParameter parameter, final Visitor<T> visitor) {
        return visitor.visitHeader(parameter);
      }
    };

    public abstract <T> T accept(RouteParameter parameter, Visitor<T> visitor);
  }

  private Kind kind;

  private String name;

  private Type type;

  private Object value;

  private String description;

  private List<Object> enums;

  /**
   * Creates a new {@link RouteParameter}.
   *
   * @param name Name.
   * @param kind Kind.
   * @param type Type.
   * @param value Default value.
   */
  public RouteParameter(final String name, final Kind kind, final Type type,
      final Object value) {
    name(name);
    kind(kind);
    type(type);
    defaultValue(value);
  }

  /** Required by Jackson. */
  protected RouteParameter() {
  }

  /**
   * Apply a {@link Visitor} and returns the computed result.
   *
   * @param visitor Visitor.
   * @param <T> Result type.
   * @return Computed result.
   */
  public <T> T accept(Visitor<T> visitor) {
    return kind.accept(this, visitor);
  }

  /**
   * Parameter name.
   *
   * @return Parameter name.
   */
  public String name() {
    return name;
  }

  /**
   * Set parameter name.
   *
   * @param name Parameter name.
   * @return This parameter.
   */
  public RouteParameter name(final String name) {
    this.name = Objects.requireNonNull(name, "Name required.");
    return this;
  }

  /**
   * Parameter type.
   *
   * @return Parameter type.
   */
  public Type type() {
    return type;
  }

  /**
   * Set parameter type.
   *
   * @param type Parameter type.
   * @return This parameter.
   */
  public RouteParameter type(Type type) {
    this.type = Objects.requireNonNull(type, "Type required.");
    return this;
  }

  /**
   * List of enum values when the {@link #type()} represents an enum.
   *
   * @return Enum values.
   */
  public List<String> enums() {
    return Optional.ofNullable(MoreTypes.getRawType(type))
        .map(Class::getEnumConstants)
        .filter(Objects::nonNull)
        .map(values -> Arrays.asList(values).stream()
            .map(value -> ((Enum) value).name())
            .collect(Collectors.toList())
        ).orElse(Collections.emptyList());
  }

  /**
   * Default value.
   *
   * @return Default Value.
   */
  public Object defaultValue() {
    return value;
  }

  /**
   * Set default value.
   *
   * @param value Default value.
   * @return This parameter.
   */
  public RouteParameter defaultValue(Object value) {
    this.value = value;
    return this;
  }

  /**
   * Parameter kind.
   *
   * @return Parameter kind.
   */
  public Kind kind() {
    return kind;
  }

  /**
   * Set parameter kind.
   *
   * @param kind Parameter kind.
   * @return This parameter.
   */
  public RouteParameter kind(Kind kind) {
    this.kind = Objects.requireNonNull(kind, "Kind required.");
    return this;
  }

  /**
   * Parameter description (if any).
   *
   * @return Parameter description (if any).
   */
  public Optional<String> description() {
    return Optional.ofNullable(description);
  }

  /**
   * Set parameter description.
   *
   * @param description Parameter description.
   * @return This parameter.
   */
  public RouteParameter description(String description) {
    this.description = Strings.emptyToNull(description);
    return this;
  }

  /**
   * True if parameter is optional. A parameter is optional when there is a default value or
   * {@link #type()} is {@link Optional}.
   *
   * @return True if parameter is optional. A parameter is optional when there is a default value or
   *     {@link #type()} is {@link Optional}.
   */
  public boolean optional() {
    return value != null || MoreTypes.getRawType(type) == Optional.class;
  }

  @Override
  public String toString() {
    StringBuilder buff = new StringBuilder();
    buff.append("@").append(kind.name().toLowerCase()).append(" ");
    buff.append(name);
    buff.append(": ").append(type.getTypeName());
    if (value != null) {
      buff.append(" = ").append(value);
    }
    return buff.toString();
  }

}


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

import static java.util.Objects.requireNonNull;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;

import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * Utility class for HTTP responses. Usually you start with a result {@link Results builder} and
 * then you customize (or not) one or more HTTP attribute.
 *
 *

 * The following examples build the same output:
 *

 *
 *

 * {
 *   get("/", (req, rsp) {@literal ->} {
 *     rsp.status(200).send("Something");
 *   });
 *
 *   get("/", req {@literal ->} Results.with("Something", 200);
 * }
 *

 *
 * A result is also responsible for content negotiation (if required):
 *
 *

 * {
 *   get("/", () {@literal ->} {
 *     Object model = ...;
 *     return Results
 *       .when("text/html", () {@literal ->} Results.html("view").put("model", model))
 *       .when("application/json", () {@literal ->} model);
 *   });
 * }
 *

 *
 *

 * The example above will render a view when accept header is "text/html" or just send a text
 * version of model when the accept header is "application/json".
 *

 *
 * @author edgar
 * @since 0.5.0
 * @see Results
 */
public class Result {

  /**
   * Content negotiation support.
   *
   * @author edgar
   */
  static class ContentNegotiation extends Result {

    private final Map<MediaType, Supplier<Object>> data = new LinkedHashMap<>();

    ContentNegotiation(final Result result) {
      this.status = result.status;
      this.type = result.type;
      this.headers = result.headers;
    }

    @Override
    public <T> T get() {
      return get(MediaType.ALL);
    }

    @Override
    public Optional<Object> ifGet() {
      return ifGet(MediaType.ALL);
    }

    @Override
    public Optional<Object> ifGet(final List<MediaType> types) {
      return Optional.ofNullable(get(types));
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> T get(final List<MediaType> types) {
      Supplier<Object> provider = MediaType
          .matcher(types)
          .first(ImmutableList.copyOf(data.keySet()))
          .map(it -> data.remove(it))
          .orElseThrow(
              () -> new Err(Status.NOT_ACCEPTABLE, Joiner.on(", ").join(types)));
      return (T) provider.get();
    }

    @Override
    public Result when(final MediaType type, final Supplier<Object> supplier) {
      requireNonNull(type, "A media type is required.");
      requireNonNull(supplier, "A supplier fn is required.");
      data.put(type, supplier);
      return this;
    }

    @Override
    protected Result clone() {
      ContentNegotiation result = new ContentNegotiation(this);
      result.data.putAll(data);
      return result;
    }

  }

  private static Map<String, Object> NO_HEADERS = ImmutableMap.of();

  /** Response headers. */
  protected Map<String, Object> headers = NO_HEADERS;

  /** Response status. */
  protected Status status;

  /** Response content-type. */
  protected MediaType type;

  /** Response value. */
  private Object value;

  /**
   * Set response status.
   *
   * @param status A new response status to use.
   * @return This content.
   */
  @Nonnull
  public Result status(final Status status) {
    this.status = requireNonNull(status, "A status is required.");
    return this;
  }

  /**
   * Set response status.
   *
   * @param status A new response status to use.
   * @return This content.
   */
  @Nonnull
  public Result status(final int status) {
    return status(Status.valueOf(status));
  }

  /**
   * Set the content type of this content.
   *
   * @param type A content type.
   * @return This content.
   */
  @Nonnull
  public Result type(final MediaType type) {
    this.type = requireNonNull(type, "A content type is required.");
    return this;
  }

  /**
   * Set the content type of this content.
   *
   * @param type A content type.
   * @return This content.
   */
  @Nonnull
  public Result type(final String type) {
    return type(MediaType.valueOf(type));
  }

  /**
   * Set result content.
   *
   * @param content A result content.
   * @return This content.
   */
  @Nonnull
  public Result set(final Object content) {
    this.value = content;
    return this;
  }

  /**
   * Add a when clause for a custom result for the given media-type.
   *
   * @param type A media type to test for.
   * @param supplier An object supplier.
   * @return This result.
   */
  @Nonnull
  public Result when(final String type, final Supplier<Object> supplier) {
    return when(MediaType.valueOf(type), supplier);
  }

  /**
   * Add a when clause for a custom result for the given media-type.
   *
   * @param type A media type to test for.
   * @param supplier An object supplier.
   * @return This result.
   */
  @Nonnull
  public Result when(final MediaType type, final Supplier<Object> supplier) {
    return new ContentNegotiation(this).when(type, supplier);
  }

  /**
   * @return headers for content.
   */
  @Nonnull
  public Map<String, Object> headers() {
    return headers;
  }

  /**
   * @return Body status.
   */
  @Nonnull
  public Optional<Status> status() {
    return Optional.ofNullable(status);
  }

  /**
   * @return Body type.
   */
  @Nonnull
  public Optional<MediaType> type() {
    return Optional.ofNullable(type);
  }

  /**
   * Get a result value.
   *
   * @return Value or empty
   */
  @Nonnull
  public Optional<Object> ifGet() {
    return ifGet(MediaType.ALL);
  }

  /**
   * Get a result value.
   *
   * @param <T> Value type.
   * @return Value or null
   */
  @SuppressWarnings("unchecked")
  @Nullable
  public <T> T get() {
    return (T) value;
  }

  /**
   * Get a result value for the given types (accept header).
   *
   * @param types Accept header.
   * @return Result content.
   */
  @Nonnull
  public Optional<Object> ifGet(final List<MediaType> types) {
    return Optional.ofNullable(value);
  }

  /**
   * Get a result value for the given types (accept header).
   *
   * @param types Accept header.
   * @param <T> Value type.
   * @return Result content or null.
   */
  @SuppressWarnings("unchecked")
  @Nullable
  public <T> T get(final List<MediaType> types) {
    return (T) value;
  }

  /**
   * Sets a response header with the given name and value. If the header had already been set,
   * the new value overwrites the previous one.
   *
   * @param name Header's name.
   * @param value Header's value.
   * @return This content.
   */
  @Nonnull
  public Result header(final String name, final Object value) {
    requireNonNull(name, "Header's name is required.");
    requireNonNull(value, "Header's value is required.");
    setHeader(name, value);
    return this;
  }

  /**
   * Sets a response header with the given name and value. If the header had already been set,
   * the new value overwrites the previous one.
   *
   * @param name Header's name.
   * @param values Header's values.
   * @return This content.
   */
  @Nonnull
  public Result header(final String name, final Object... values) {
    requireNonNull(name, "Header's name is required.");
    requireNonNull(values, "Header's values are required.");

    return header(name, ImmutableList.copyOf(values));
  }

  /**
   * Sets a response header with the given name and value. If the header had already been set,
   * the new value overwrites the previous one.
   *
   * @param name Header's name.
   * @param values Header's values.
   * @return This content.
   */
  @Nonnull
  public Result header(final String name, final Iterable<Object> values) {
    requireNonNull(name, "Header's name is required.");
    requireNonNull(values, "Header's values are required.");
    setHeader(name, values);
    return this;
  }

  @Override
  protected Result clone() {
    Result result = new Result();
    headers.forEach(result::header);
    result.status = status;
    result.type = type;
    result.value = value;
    return result;
  }

  private void setHeader(final String name, final Object val) {
    headers = ImmutableMap.<String, Object> builder()
        .putAll(headers)
        .put(name, val)
        .build();
  }

}


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

import com.google.common.collect.ImmutableList;
import com.google.inject.Binder;
import com.google.inject.Key;
import com.google.inject.name.Names;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import io.ebean.EbeanServer;
import io.ebean.config.ContainerConfig;
import io.ebean.config.ServerConfig;
import static java.util.Objects.requireNonNull;
import org.jooby.Env;
import org.jooby.Env.ServiceKey;
import org.jooby.Jooby;
import org.jooby.funzy.Throwing;
import org.jooby.internal.ebean.EbeanEnhancer;
import org.jooby.internal.ebean.EbeanManaged;
import org.jooby.jdbc.Jdbc;

import javax.sql.DataSource;
import java.util.HashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

/**
 *
ebean module

 *

 * Object-Relational-Mapping via Ebean. It configures and exposes {@link EbeanServer} instances.
 *

 *

 * This module extends {@link Jdbc} module, before going forward, make sure you read the doc of the
 * {@link Jdbc} module first.
 *

 *
 *
usage

 *

 * {
 *   use(new Ebeanby().doWith(conf {@literal ->} {
 *    conf.addClass(Pet.class);
 *   }));
 *
 *   get("/pets", req {@literal ->} {
 *     EbeanServer ebean = req.require(EbeanServer.class);
 *     return ebean.createQuery(Pet.class)
 *        .findList();
 *   });
 * }
 *

 *
 *

 * Usage is pretty straightforward, but of course we need to setup/configure the enhancement.
 *

 *
 *
enhancement

 *

 * The enhancement process comes in two flavors:
 *

 *

 *
Runtime: via a JVM Agent

 *
Build time: via Maven plugin

 *

 *
 *
recommended setup

 *

 * The recommended setup consist of setting up both: runtime and build time enhancement.
 *

 *
 *

 * The runtime enhancer increases developer productivity, it let you start your app from IDE
 * and/or mvn jooby:run. All you have to do is to add the agent dependencies to your
 * classpath:
 *

 *
 *

 * <dependency>
 *   <groupId>org.avaje.ebeanorm</groupId>
 *   <artifactId>avaje-ebeanorm-agent</artifactId>
 *   <scope>test</scope>
 * </dependency>
 *
 * <dependency>
 *   <groupId>org.avaje</groupId>
 *   <artifactId>avaje-agentloader</artifactId>
 *   <scope>test</scope>
 * </dependency>
 *

 *
 *

 * Did you see the test scope? We don't want to use the runtime enhancer while
 * running in prod. Instead, we want to use the build time enhancer.
 *

 *

 * All you have to do is to add avaje-ebeanorm-mavenenhancer to your
 * pom.xml as described in the
 * official doc.
 *

 *
 *

 * Alternative, and because we want to keep our pom.xml small, you can drop a
 * ebean.activator file inside the src/etc/mvn folder. The presence of the
 * file src/etc/mvn/ebean.activator will trigger the
 * avaje-ebeanorm-mavenenhancer plugin.
 *

 *
 *
configuration

 *

 * Configuration is done via .conf, for example:
 *

 *
 *

 * ebean.ddl.generate=false
 * ebean.ddl.run=false
 *
 * ebean.debug.sql=true
 * ebean.debug.lazyload=false
 *
 * ebean.disableClasspathSearch = false
 *

 *
 *

 * Or programmatically:
 *

 *
 *

 * {
 *   use(new Ebeanby().doWith(conf {@literal ->} {
 *     conf.setDisableClasspathSearch(false);
 *   }));
 * }
 *

 *
 * @author edgar
 * @since 0.10.0
 */
public class Ebeanby implements Jooby.Module {

  /** package for test */
  static final AtomicReference<Set<String>> PKG = new AtomicReference<>(new HashSet<>());

  static {
    // Turn off ebean shutdown hook:
    System.setProperty("ebean.registerShutdownHook", "false");
  }

  /** Database name. */
  private String name;

  private BiConsumer<ServerConfig, Config> callback;

  /**
   * Creates a new {@link Ebeanby} using the given name to setup a {@link Jdbc} datasource.
   *
   * @param name Name of this ebean module.
   */
  public Ebeanby(final String name) {
    this.name = name;
  }

  /**
   * Creates a new {@link Ebeanby} using the default {@link Jdbc} name: db.
   */
  public Ebeanby() {
    this("db");
  }

  @Override
  public void configure(final Env env, final Config conf, final Binder binder) {
    ServerConfig config = new ServerConfig();

    config.setName(name);

    Config cprops = conf.getConfig("ebean");
    if (conf.hasPath("ebean." + name)) {
      cprops = conf.getConfig("ebean." + name)
          .withFallback(cprops)
          .withoutPath(name);
    }

    Properties props = props(cprops);

    ContainerConfig container = new ContainerConfig();
    container.loadFromProperties(props);

    Key<DataSource> dskey = Key.get(DataSource.class, Names.named(name));
    DataSource ds = env.get(dskey)
        .orElseThrow(() -> new NoSuchElementException("DataSource missing: " + dskey));

    config.setDataSource(ds);
    config.setContainerConfig(container);
    config.loadFromProperties(props);
    config.setDefaultServer(cprops.getBoolean("defaultServer"));
    config.setRegister(cprops.getBoolean("register"));

    if (callback != null) {
      callback.accept(config, conf);
    }

    List<String> packages = config.getPackages();
    if (packages == null || packages.size() == 0) {
      packages = ImmutableList.of(conf.getString("application.ns"));
    }
    config.setPackages(packages);
    if (PKG.get() != null) {
      PKG.get().addAll(packages);
    }

    EbeanManaged ebean = new EbeanManaged(conf, config);
    env.onStart(ebean::start);
    env.onStop(ebean::stop);
    /** Bind db key: */
    Consumer<Key<EbeanServer>> provider = k -> binder.bind(k).toProvider(ebean);
    ServiceKey keys = env.serviceKey();
    keys.generate(EbeanServer.class, name, provider);

    // Run enhancer once per JVM
    env.onStart(runEnhancer());
  }

  public Ebeanby doWith(BiConsumer<ServerConfig, Config> configurer) {
    this.callback = requireNonNull(configurer, "Configurer required.");
    return this;
  }

  public Ebeanby doWith(Consumer<ServerConfig> configurer) {
    requireNonNull(configurer, "Configurer required.");
    return doWith((server, conf) -> configurer.accept(server));
  }

  @Override
  public Config config() {
    return ConfigFactory.parseResources(getClass(), "ebean.conf");
  }

  private Properties props(final Config config) {
    Properties props = new Properties();

    config.entrySet().forEach(prop -> {
      Object value = prop.getValue().unwrapped();
      props.setProperty("ebean." + prop.getKey(), value.toString());
    });
    return props;
  }

  /**
   * package for test.
   *
   * @return An enhancer task. It runs once per classloader instance.
   */
  static Throwing.Runnable runEnhancer() {
    return () -> {
      Set<String> packages = PKG.getAndSet(null);
      if (packages != null) {
        EbeanEnhancer.newEnhancer().run(packages);
      }
    };
  }

}


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

import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.collect.ImmutableMap;
import org.jooby.MediaType;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class RamlMethod {

  private final transient String name;

  private String displayName;

  private String description;

  private Map<String, RamlParameter> queryParameters;

  private Map<String, RamlParameter> formParameters;

  private Map<String, RamlParameter> headers;

  private RamlType body;

  private List<String> mediaType;

  private Map<Integer, RamlResponse> responses;

  /**
   * Creates a new RAML method.
   *
   * @param name Method name.
   */
  public RamlMethod(String name) {
    this.name = name;
  }

  /**
   * Input/Request type.
   *
   * @return Input/Request type.
   */
  @JsonIgnore
  public RamlType getBody() {
    return body;
  }

  /**
   * Set input/request type.
   *
   * @param body RAML type.
   */
  public void setBody(final RamlType body) {
    this.body = body;
  }

  /**
   * Method display name.
   *
   * @return Display name.
   */
  public String getDisplayName() {
    return displayName;
  }

  /**
   * Set display name.
   *
   * @param displayName Method display name.
   */
  public void setDisplayName(final String displayName) {
    this.displayName = displayName;
  }

  /**
   * Method description.
   *
   * @return Method description.
   */
  public String getDescription() {
    return description;
  }

  /**
   * Set method description.
   *
   * @param description Description.
   */
  public void setDescription(final String description) {
    this.description = description;
  }

  /**
   * Map of query parameters.
   * @return Query parameters.
   */
  public Map<String, RamlParameter> getQueryParameters() {
    return queryParameters;
  }

  /**
   * Set query parameters.
   *
   * @param queryParameters Query parameters.
   */
  public void setQueryParameters(
      final Map<String, RamlParameter> queryParameters) {
    this.queryParameters = queryParameters;
  }

  /**
   * Map of header parameters.
   *
   * @return Header parameters.
   */
  public Map<String, RamlParameter> getHeaders() {
    return headers;
  }

  /**
   * Set header parameters.
   *
   * @param headers Header parameters.
   */
  public void setHeaders(final Map<String, RamlParameter> headers) {
    this.headers = headers;
  }

  /**
   * Map of status codes.
   *
   * @return Status Code.
   */
  public Map<Integer, RamlResponse> getResponses() {
    return responses;
  }

  /**
   * Set status codes response.
   *
   * @param responses Response.
   */
  public void setResponses(final Map<Integer, RamlResponse> responses) {
    this.responses = responses;
  }

  /**
   * Request media types.
   * @return Request media types.
   */
  @JsonIgnore
  public List<String> getMediaType() {
    return mediaType;
  }

  /**
   * Set media types.
   *
   * @param mediaType Media types.
   */
  public void setMediaType(final List<String> mediaType) {
    this.mediaType = mediaType == null ? null : (mediaType.isEmpty() ? null : mediaType);
  }

  /**
   * Form parameters.
   *
   * @return Form parameters.
   */
  @JsonIgnore
  public Map<String, RamlParameter> getFormParameters() {
    return formParameters;
  }

  /**
   * Set form parameters.
   *
   * @param formParameters Form parameters.
   */
  public void setFormParameters(
      final Map<String, RamlParameter> formParameters) {
    this.formParameters = formParameters;
  }

  /**
   * Get or create a query parameter using the giving name.
   *
   * @param name Parameter name.
   * @return Query parameter.
   */
  public RamlParameter queryParameter(String name) {
    if (queryParameters == null) {
      queryParameters = new LinkedHashMap<>();
    }
    RamlParameter param = queryParameters.get(name);
    if (param == null) {
      param = new RamlParameter(name);
      queryParameters.put(name, param);
    }
    return param;
  }

  /**
   * Get or create a form parameter using the giving name.
   *
   * @param name Parameter name.
   * @return Form parameter.
   */
  public RamlParameter formParameter(String name) {
    if (formParameters == null) {
      formParameters = new LinkedHashMap<>();
    }
    RamlParameter param = formParameters.get(name);
    if (param == null) {
      param = new RamlParameter(name);
      formParameters.put(name, param);
    }
    return param;
  }

  /**
   * Get or create a header parameter using the giving name.
   *
   * @param name Parameter name.
   * @return Header parameter.
   */
  public RamlParameter headerParameter(String name) {
    if (headers == null) {
      headers = new LinkedHashMap<>();
    }
    RamlParameter param = headers.get(name);
    if (param == null) {
      param = new RamlParameter(name);
      headers.put(name, param);
    }
    return param;
  }

  /**
   * Get or create a response using the given status code.
   *
   * @param status Status code.
   * @return RAML response.
   */
  public RamlResponse response(Integer status) {
    if (responses == null) {
      responses = new LinkedHashMap<>();
    }
    RamlResponse response = responses.get(status);
    if (response == null) {
      response = new RamlResponse();
      responses.put(status, response);
    }
    return response;
  }

  @JsonAnyGetter
  Map<String, Object> attributes() {
    Map<String, Object> attributes = new LinkedHashMap<>();
    if (formParameters != null) {
      attributes.put("body",
          ImmutableMap
              .of(MediaType.multipart.name(), ImmutableMap.of("properties", formParameters)));
    } else if (body != null) {
      if (mediaType != null) {
        attributes.put("body", mediaType.stream()
            .collect(Collectors.toMap(Function.identity(), it -> body.getRef())));
      } else {
        attributes.put("body", body.getRef());
      }
    } else if (mediaType != null) {
      attributes.put("body", mediaType.stream()
          .collect(Collectors.toMap(Function.identity(), it -> ImmutableMap.of())));
    }
    return attributes;
  }
}