/**
 *                                  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 javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.ForkJoinPool;

/**
 *
async request processing

 *

 * A Deferred result, useful for async request processing.
 *

 *

 * Application can produces a result from a different thread. Once result is ready, a call to
 * {@link #resolve(Object)} is required. Please note, a call to {@link #reject(Throwable)} is
 * required in case of errors.
 *

 *
 *
usage

 *
 *

 * {
 *    get("/async", deferred(() {@literal ->} {
 *      return "Success";
 *    }));
 *  }
 *

 *
 * From MVC route:
 *
 *
{@code
 *
 *  public class Controller {
 *    @GET
 *    @Path("/async")
 *    public Deferred async() {
 *      return Deferred.deferred(() -> "Success");
 *    }
 *  }
 * }

 *
 * If you add the {@link AsyncMapper} then your controller method can return a {@link Callable}.
 *
 * Previous example runs in the default executor, which always run deferred results in the
 * same/caller thread.
 *
 * To effectively run a deferred result in new/different thread you need to provide an
 * {@link Executor}:
 *
 *
{@code
 * {
 *   executor(new ForkJoinPool());
 * }
 * }

 *
 * This line override the default executor with a {@link ForkJoinPool}. You can add two or more
 * named executor:
 *
 *
{@code
 * {
 *   executor(new ForkJoinPool());
 *
 *   executor("cached", Executors.newCachedExecutor());
 *
 *   get("/async", deferred("cached", () -> "Success"));
 * }
 * }

 *
 * A {@link Deferred} object works as a promise too, given you {@link #resolve(Object)} and
 * {@link #reject(Throwable)} methods. Examples:
 *
 * As promise using the default executor (execute promise in same/caller thread):
 *

 * {
 *    get("/async", promise(deferred {@literal ->} {
 *      try {
 *        deferred.resolve(...); // success value
 *      } catch (Throwable ex) {
 *        deferred.reject(ex); // error value
 *      }
 *    }));
 *  }
 *

 *
 * As promise using a custom executor:
 *

 * {
 *    executor(new ForkJoinPool());
 *
 *    get("/async", promise(deferred {@literal ->} {
 *      try {
 *        deferred.resolve(...); // success value
 *      } catch (Throwable ex) {
 *        deferred.reject(ex); // error value
 *      }
 *    }));
 *  }
 *

 *
 * As promise using an alternative executor:
 *
 *

 * {
 *    executor(new ForkJoinPool());
 *
 *    executor("cached", Executors.newCachedExecutor());
 *
 *    get("/async", promise("cached", deferred {@literal ->} {
 *      try {
 *        deferred.resolve(...); // success value
 *      } catch (Throwable ex) {
 *        deferred.reject(ex); // error value
 *      }
 *    }));
 *  }
 *

 *
 * @author edgar
 * @since 0.10.0
 */
public class Deferred extends Result {

  /**
   * Deferred initializer, useful to provide a more functional API.
   *
   * @author edgar
   * @since 0.10.0
   */
  public interface Initializer0 {

    /**
     * Run the initializer block.
     *
     * @param deferred Deferred object.
     * @throws Exception If something goes wrong.
     */
    void run(Deferred deferred) throws Exception;
  }

  /**
   * Deferred initializer with {@link Request} access, useful to provide a more functional API.
   *
   * @author edgar
   * @since 0.10.0
   */
  public interface Initializer {

    /**
     * Run the initializer block.
     *
     * @param req Current request.
     * @param deferred Deferred object.
     * @throws Exception If something goes wrong.
     */
    void run(Request req, Deferred deferred) throws Exception;
  }

  /**
   * A deferred handler. Application code should never use this class. INTERNAL USE ONLY.
   *
   * @author edgar
   * @since 0.10.0
   */
  public interface Handler {
    void handle(@Nullable Result result, Throwable exception);
  }

  /** Deferred initializer. Optional. */
  private Initializer initializer;

  /** Deferred handler. Internal. */
  private Handler handler;

  private String executor;

  private String callerThread;

  /**
   * Creates a new {@link Deferred} with an initializer.
   *
   * @param executor Executor to use.
   * @param initializer An initializer.
   */
  public Deferred(final String executor, final Initializer0 initializer) {
    this(executor, (req, deferred) -> initializer.run(deferred));
  }

  /**
   * Creates a new {@link Deferred} with an initializer.
   *
   * @param initializer An initializer.
   */
  public Deferred(final Initializer0 initializer) {
    this(null, initializer);
  }

  /**
   * Creates a new {@link Deferred} with an initializer.
   *
   * @param initializer An initializer.
   */
  public Deferred(final Initializer initializer) {
    this(null, initializer);
  }

  /**
   * Creates a new {@link Deferred} with an initializer.
   *
   * @param executor Executor to use.
   * @param initializer An initializer.
   */
  public Deferred(@Nullable final String executor, final Initializer initializer) {
    this.executor = executor;
    this.initializer = requireNonNull(initializer, "Initializer is required.");
    this.callerThread = Thread.currentThread().getName();
  }

  /**
   * Creates a new {@link Deferred}.
   */
  public Deferred() {
  }

  /**
   * {@link #resolve(Object)} or {@link #reject(Throwable)} the given value.
   *
   * @param value Resolved value.
   */
  @Override
  @Nonnull
  public Result set(final Object value) {
    if (value instanceof Throwable) {
      reject((Throwable) value);
    } else {
      resolve(value);
    }
    return this;
  }

  /**
   * Get an executor to run this deferred result. If the executor is present, then it will be use it
   * to execute the deferred object. Otherwise it will use the global/application executor.
   *
   * @return Executor to use or fallback to global/application executor.
   */
  @Nonnull
  public Optional<String> executor() {
    return Optional.ofNullable(executor);
  }

  /**
   * Name of the caller thread (thread that creates this deferred object).
   *
   * @return Name of the caller thread (thread that creates this deferred object).
   */
  @Nonnull
  public String callerThread() {
    return callerThread;
  }

  /**
   * Resolve the deferred value and handle it. This method will send the response to a client and
   * cleanup and close all the resources.
   *
   * @param value A value for this deferred.
   */
  public void resolve(@Nullable final Object value) {
    if (value == null) {
      handler.handle(null, null);
    } else {
      Result result;
      if (value instanceof Result) {
        super.set(value);
        result = (Result) value;
      } else {
        super.set(value);
        result = clone();
      }
      handler.handle(result, null);
    }
  }

  /**
   * Resolve the deferred with an error and handle it. This method will handle the given exception,
   * send the response to a client and cleanup and close all the resources.
   *
   * @param cause A value for this deferred.
   */
  public void reject(final Throwable cause) {
    super.set(cause);
    handler.handle(null, cause);
  }

  /**
   * Setup a handler for this deferred. Application code should never call this method: INTERNAL USE
   * ONLY.
   *
   * @param req Current request.
   * @param handler A response handler.
   * @throws Exception If initializer fails to start.
   */
  public void handler(final Request req, final Handler handler) throws Exception {
    this.handler = requireNonNull(handler, "Handler is required.");
    if (initializer != null) {
      initializer.run(req, this);
    }
  }

  /**
   * Functional version of {@link Deferred#Deferred(Initializer)}.
   *
   * Using the default executor (current thread):
   *
   *
{@code
   * {
   *   get("/fork", deferred(req -> {
   *     return req.param("value").value();
   *   }));
   * }
   * }

   *
   * Using a custom executor:
   *
   *
{@code
   * {
   *   executor(new ForkJoinPool());
   *
   *   get("/fork", deferred(req -> {
   *     return req.param("value").value();
   *   }));
   * }
   * }

   *
   * This handler automatically {@link Deferred#resolve(Object)} or
   * {@link Deferred#reject(Throwable)} a route handler response.
   *
   * @param handler Application block.
   * @return A new deferred handler.
   */
  @Nonnull
  public static Deferred deferred(final Route.OneArgHandler handler) {
    return deferred(null, handler);
  }

  /**
   * Functional version of {@link Deferred#Deferred(Initializer)}.
   *
   * Using the default executor (current thread):
   *
   *
{@code
   * {
   *   get("/fork", deferred(() -> {
   *     return req.param("value").value();
   *   }));
   * }
   * }

   *
   * Using a custom executor:
   *
   *
{@code
   * {
   *   executor(new ForkJoinPool());
   *
   *   get("/fork", deferred(() -> {
   *     return req.param("value").value();
   *   }));
   * }
   * }

   *
   * This handler automatically {@link Deferred#resolve(Object)} or
   * {@link Deferred#reject(Throwable)} a route handler response.
   *
   * @param handler Application block.
   * @return A new deferred.
   */
  @Nonnull
  public static Deferred deferred(final Route.ZeroArgHandler handler) {
    return deferred(null, handler);
  }

  /**
   * Functional version of {@link Deferred#Deferred(Initializer)}. To use ideally with one
   * or more {@link Executor}:
   *
   *
{@code
   * {
   *   executor("cached", Executors.newCachedExecutor());
   *
   *   get("/fork", deferred("cached", () -> {
   *     return "OK";
   *   }));
   * }
   * }

   *
   * This handler automatically {@link Deferred#resolve(Object)} or
   * {@link Deferred#reject(Throwable)} a route handler response.
   *
   * @param executor Executor to run the deferred.
   * @param handler Application block.
   * @return A new deferred handler.
   */
  @Nonnull
  public static Deferred deferred(final String executor, final Route.ZeroArgHandler handler) {
    return deferred(executor, req -> handler.handle());
  }

  /**
   * Functional version of {@link Deferred#Deferred(Initializer)}. To use ideally with one
   * or more {@link Executor}:
   *
   *
{@code
   * {
   *   executor("cached", Executors.newCachedExecutor());
   *
   *   get("/fork", deferred("cached", req -> {
   *     return req.param("value").value();
   *   }));
   * }
   * }

   *
   * This handler automatically {@link Deferred#resolve(Object)} or
   * {@link Deferred#reject(Throwable)} a route handler response.
   *
   * @param executor Executor to run the deferred.
   * @param handler Application block.
   * @return A new deferred handler.
   */
  @Nonnull
  public static Deferred deferred(final String executor, final Route.OneArgHandler handler) {
    return new Deferred(executor, (req, deferred) -> {
      try {
        deferred.resolve(handler.handle(req));
      } catch (Throwable x) {
        deferred.reject(x);
      }
    });
  }

}


/**
 *                                  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.JsonInclude;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.inject.internal.MoreTypes;
import io.swagger.converter.ModelConverters;
import io.swagger.models.Model;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.PropertyBuilder;
import io.swagger.models.properties.RefProperty;
import io.swagger.models.properties.StringProperty;
import io.swagger.models.properties.UUIDProperty;
import org.jooby.MediaType;
import org.jooby.apitool.RouteMethod;
import org.jooby.apitool.RouteParameter;
import org.jooby.apitool.RouteResponse;
import org.jooby.internal.apitool.FriendlyTypeName;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.EnumMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * RAML objects for describing a RAML definition file. This is a partial representation of the RAML
 * specification.
 *
 * @since 1.2.0
 * @author edgar
 */
public class Raml {
  private String title;

  private String version;

  private String baseUri;

  private List<String> mediaType;

  private List<String> protocols;

  private Map<String, RamlType> types;

  private Map<String, RamlPath> resources = new LinkedHashMap<>();

  /**
   * RAML title.
   *
   * @return RAML title.
   */
  public String getTitle() {
    return title;
  }

  /**
   * Set RAML title.
   *
   * @param title RAML title.
   */
  public void setTitle(final String title) {
    this.title = title;
  }

  /**
   * RAML version.
   *
   * @return RAML version.
   */
  public String getVersion() {
    return version;
  }

  /**
   * Set RAML version.
   *
   * @param version RAML version.
   */
  public void setVersion(final String version) {
    this.version = version;
  }

  /**
   * RAML base uri.
   *
   * @return RAML base uri.
   */
  public String getBaseUri() {
    return baseUri;
  }

  /**
   * Set base uri.
   *
   * @param baseUri Base uri.
   */
  public void setBaseUri(final String baseUri) {
    this.baseUri = baseUri;
  }

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

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

  /**
   * Get protocols.
   *
   * @return Protocols.
   */
  public List<String> getProtocols() {
    return protocols;
  }

  /**
   * Set protocols.
   *
   * @param protocols Protocols.
   */
  public void setProtocols(final List<String> protocols) {
    this.protocols = protocols;
  }

  /**
   * RAML types.
   *
   * @return RAML types.
   */
  public Map<String, RamlType> getTypes() {
    return types;
  }

  /**
   * Get resources.
   *
   * @return Resources.
   */
  @JsonAnyGetter
  public Map<String, RamlPath> getResources() {
    return resources;
  }

  /**
   * Get a path for the given pattern. If the path doesn't exist, a new path will be created.
   *
   * @param pattern Pattern.
   * @return Path for the given pattern.
   */
  public RamlPath path(String pattern) {
    RamlPath path = resources.get(pattern);
    if (path == null) {
      path = new RamlPath();
      resources.put(pattern, path);
    }
    return path;
  }

  /**
   * Define/map a custom Java type to RAML type.
   *
   * <pre>
   *   RamlType uuid = raml.define(UUID.class, RamlType.STRING);
   *   uuid.setPattern("...");
   * </pre>
   *
   * @param javaType Java type.
   * @param baseType RAML base type.
   * @return New RAML type.
   */
  public RamlType define(Type javaType, RamlType baseType) {
    Objects.requireNonNull(javaType, "Java type required.");
    Objects.requireNonNull(baseType, "Raml type required.");
    if (types == null) {
      types = new LinkedHashMap<>();
    }
    String typeName = MoreTypes.getRawType(javaType).getSimpleName();
    RamlType ramlType = new RamlType(baseType.getType(), typeName);
    types.put(typeName, ramlType);
    return ramlType;
  }

  /**
   * Register a Java type and produces an equivalent RAML type. It returns an existing RAML type if
   * the Java type was registered already.
   *
   * @param type Java type.
   * @return RAML type.
   */
  public RamlType define(Type type) {
    if (types == null) {
      types = new LinkedHashMap<>();
    }
    Type componentType = componentType(type);
    String typeName = MoreTypes.getRawType(componentType).getSimpleName();
    RamlType ramlType = RamlType.valueOf(typeName);
    if (ramlType.isObject()) {
      RamlType existing = types.get(typeName);
      if (existing == null) {
        ModelConverters converter = ModelConverters.getInstance();
        Property property = converter.readAsProperty(componentType);

        Map<PropertyBuilder.PropertyId, Object> args = new EnumMap<>(
            PropertyBuilder.PropertyId.class);
        for (Map.Entry<String, Model> entry : converter.readAll(componentType).entrySet()) {
          define(entry.getKey(), entry.getValue());
        }
        ramlType = define(typeName, PropertyBuilder.toModel(PropertyBuilder.merge(property, args)));
      } else {
        ramlType = existing;
      }
    }

    return type != componentType ? ramlType.toArray() : ramlType;
  }

  private Type componentType(final Type type) {
    Class<?> rawType = MoreTypes.getRawType(type);
    if (rawType.isArray()) {
      return rawType.getComponentType();
    }
    if (Collection.class.isAssignableFrom(rawType) && type instanceof ParameterizedType) {
      return ((ParameterizedType) type).getActualTypeArguments()[0];
    }
    return type;
  }

  private RamlType define(final String type, final Model model) {
    RamlType definition = types.get(type);
    if (definition == null) {
      RamlType object = new RamlType("object", type);
      types.put(type, object);
      Map<String, Object> example = new LinkedHashMap<>();
      Optional.ofNullable(model.getProperties())
          .ifPresent(properties -> properties.forEach((name, property) -> {
            if (property instanceof RefProperty) {
              String propertyType = propertyType(property);
              object.newProperty(name, propertyType, false);
            } else if (property instanceof ArrayProperty) {
              String propertyType = propertyType(((ArrayProperty) property).getItems()) + "[]";
              object.newProperty(name, propertyType, false);
            } else {
              String propertyType = propertyType(property);
              List<String> enums = null;
              if (property instanceof StringProperty) {
                enums = ((StringProperty) property).getEnum();
              }
              RamlType ramlType = RamlType.valueOf(propertyType);
              // String propertyType = ramlType.isObject() ? property.getType() : ramlType.getType();
              object.newProperty(name, propertyType, false,
                  Optional.ofNullable(enums).map(it -> it.toArray(new String[it.size()]))
                      .orElse(new String[0]));
              example.put(name, Optional.ofNullable(enums).<Object>map(it -> it.get(0))
                  .orElse(ramlType.getExample()));
            }
          }));
      definition = object;
      if (example.values().stream().filter(Objects::nonNull).count() > 0) {
        object.setExample(example);
      }
    }
    return definition;
  }

  private String propertyType(Property property) {
    if (property instanceof RefProperty) {
      return ((RefProperty) property).getSimpleRef();
    }
    // Special handling for uuid type reported by Swagger converter
    String type = property.getType();
    if (property instanceof UUIDProperty) {
      type = UUID.class.getSimpleName();
    }
    RamlType ramlType = types.get(type);
    return ramlType == null ? property.getType() : ramlType.getRef().getType();
  }

  /**
   * Set RAML paths.
   *
   * @param resources RAML paths.
   */
  public void setResources(final Map<String, RamlPath> resources) {
    this.resources = resources;
  }

  /**
   * Convert this RAML object to Yaml.
   *
   * @return Yaml string.
   * @throws IOException If something goes wrong.
   */
  public String toYaml() throws IOException {
    YAMLMapper mapper = new YAMLMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, false);
    mapper.configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true);
    return "#%RAML 1.0\n" + mapper.writer().withDefaultPrettyPrinter().writeValueAsString(this);
  }

  /**
   * Build a {@link Raml} object from list of {@link RouteMethod}.
   *
   * @param base Base raml (might be null).
   * @param routes List of routes.
   * @return RAML object.
   */
  public static Raml build(Raml base, List<RouteMethod> routes) {
    Raml raml = Optional.ofNullable(base).orElseGet(Raml::new);
    BiFunction<RamlPath, String, RamlPath> pathFactory = (path, segment) ->
        path == null ? raml.path(segment) : path.path(segment);

    BiConsumer<Function<String, RamlParameter>, RouteParameter> parameterFactory = (factory, parameter) -> {
      RamlParameter p = factory.apply(parameter.name());
      p.setDescription(parameter.description()
          .map(Raml::yamlText)
          .orElse(null));
      List<String> enums = parameter.enums();
      if (enums.size() > 0) {
        p.setType(RamlType.STRING);
        p.setEnum(enums);
      } else {
        p.setType(raml.define(parameter.type()));
      }
      p.setRequired(!parameter.optional());
      p.setDefault(parameter.defaultValue());
    };

    /** Default consumes/produces: */
    Set<String> alltypes = new LinkedHashSet<>();
    Consumer<Function<RouteMethod, List<String>>> mediaTypes = types ->
        routes.stream().forEach(r -> types.apply(r).forEach(alltypes::add));
    mediaTypes.accept(RouteMethod::consumes);
    mediaTypes.accept(RouteMethod::produces);
    boolean defaultMediaType = false;
    if (alltypes.size() == 0) {
      raml.setMediaType(ImmutableList.of(MediaType.json.name()));
      defaultMediaType = true;
    } else if (alltypes.size() == 1) {
      raml.setMediaType(ImmutableList.of(alltypes.iterator().next()));
      defaultMediaType = true;
    }

    for (RouteMethod route : routes) {
      List<String> segments = Splitter.on("/")
          .trimResults()
          .omitEmptyStrings()
          .splitToList(route.pattern());
      RamlPath path = null;
      for (String segment : segments) {
        RamlPath newPath = pathFactory.apply(path, "/" + segment);
        if (segment.startsWith("{") && segment.endsWith("}")) {
          String pathvar = segment.substring(1, segment.length() - 1);
          route.parameters().stream()
              .filter(it -> it.kind() == RouteParameter.Kind.PATH)
              .filter(it -> it.name().equals(pathvar))
              .findFirst()
              .ifPresent(it -> parameterFactory.accept(newPath::uriParameter, it));
        }
        path = newPath;
      }
      path = Optional.ofNullable(path).orElseGet(() -> raml.path("/"));
      path.setDescription(route.summary()
          .map(Raml::yamlText)
          .orElse(null));
      RamlMethod method = path.method(route.method());
      method.setDescription(route.description()
          .map(Raml::yamlText)
          .orElse(null));

      /** Check for files, if we find one use multipart to render them: */
      List<RouteParameter> files = route.parameters().stream()
          .filter(it -> it.kind() == RouteParameter.Kind.FILE)
          .collect(Collectors.toList());
      if (files.size() > 0) {
        route.parameters().stream()
            .filter(it -> it.kind() == RouteParameter.Kind.QUERY)
            .forEach(it -> parameterFactory.accept(method::formParameter, it));
        files.forEach(it -> {
          parameterFactory.accept(method::formParameter, it);
          method.setMediaType(ImmutableList.of(MediaType.multipart.name()));
        });
      } else {
        route.parameters().stream()
            .filter(it -> it.kind() == RouteParameter.Kind.QUERY)
            .forEach(it -> parameterFactory.accept(method::queryParameter, it));
      }
      /** Consumes: */
      List<String> consumes = route.consumes();
      if (consumes.size() == 0 && !defaultMediaType) {
        consumes = ImmutableList.of(MediaType.json.name());
      }
      method.setMediaType(consumes);

      /** Headers: */
      route.parameters().stream()
          .filter(it -> it.kind() == RouteParameter.Kind.HEADER)
          .forEach(it -> parameterFactory.accept(method::headerParameter, it));

      /** Body: */
      route.parameters().stream()
          .filter(it -> it.kind() == RouteParameter.Kind.BODY)
          .forEach(it -> {
            method.setMediaType(route.consumes());
            method.setBody(raml.define(it.type()));
          });
      /** Response: */
      List<String> produces = route.produces();
      if (produces.size() == 0) {
        produces = ImmutableList.of(MediaType.json.name());
      }
      RouteResponse returns = route.response();
      Map<Integer, String> status = returns.status();
      Integer statusCode = returns.statusCode();
      RamlResponse response = method.response(statusCode);
      response.setDescription(yamlText(returns.description().orElseGet(() -> FriendlyTypeName
          .name(returns.type()))));
      produces.forEach(type -> response.setMediaType(type, raml.define(returns.type())));
      status.entrySet().stream()
          .filter(it -> !statusCode.equals(it.getKey()))
          .forEach(it -> method.response(it.getKey()).setDescription(it.getValue()));
    }

    return raml;
  }

  static String yamlText(String text) {
    return Optional.ofNullable(text).map(lines ->
        Splitter.on("\n")
            .trimResults()
            .omitEmptyStrings()
            .splitToList(lines)
            .stream()
            .collect(Collectors.joining("\n"))
    ).orElse(null);
  }
}


/**
 *                                  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.common.collect.ImmutableMap;

import java.lang.reflect.Type;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * Represent a route response type.
 *
 * @since 1.2.0
 * @author edgar
 */
public class RouteResponse {
  private Type type;
  private String description;
  private Map<Integer, String> status;

  /**
   * Creates a new {@link RouteResponse}.
   *
   * @param type Return type.
   */
  public RouteResponse(Type type) {
    type(type);
  }

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

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

  /**
   * Set return type.
   *
   * @param type Type.
   * @return This response.
   */
  public RouteResponse type(Type type) {
    this.type = Objects.requireNonNull(type, "Return type required.");
    return this;
  }

  /**
   * Get response description.
   *
   * @return Response description.
   */
  public Optional<String> description() {
    return Optional.ofNullable(description);
  }

  /**
   * Set a description.
   *
   * @param description Description.
   * @return This response.
   */
  public RouteResponse description(final String description) {
    this.description = Strings.emptyToNull(description);
    return this;
  }

  /**
   * Get status codes.
   *
   * @return Status codes.
   */
  public Map<Integer, String> status() {
    return Optional.ofNullable(status).orElse(ImmutableMap.of());
  }

  /**
   * Status code.
   *
   * @return Status code.
   */
  public int statusCode() {
    return status().entrySet().stream()
        .map(it -> it.getKey())
        .filter(code -> code >= 200 && code < 400)
        .findFirst()
        .orElseGet(() -> type() == void.class ? 204 : 200);
  }

  /**
   * Set status code map.
   *
   * @param status Status code map.
   * @return This response.
   */
  public RouteResponse status(final Map<Integer, String> status) {
    if (status != null) {
      if (this.status == null) {
        this.status = new LinkedHashMap<>();
        this.status.putAll(status);
      }
    }
    return this;
  }

  /**
   * Get a description for given status code.
   *
   * @param status Status code.
   * @return Description.
   */
  public Optional<String> status(int status) {
    return Optional.ofNullable(status().get(status));
  }

  @Override public String toString() {
    return type + " => " + status();
  }
}


/**
 *                                  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 java.util.LinkedHashMap;
import java.util.Map;

/**
 * RAML response.
 *
 * @author edgar
 * @since 1.2.0
 */
public class RamlResponse {
  private String description;
  private Map<String, RamlType> mediaType;

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

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

  @JsonAnyGetter
  Map<String, Object> attributes() {
    Map<String, Object> attributes = new LinkedHashMap<>();
    if (mediaType != null) {
      Map<String, Object> body = new LinkedHashMap<>();
      mediaType.forEach((type, bodyType) -> body.put(type, bodyType.getRef()));
      attributes.put("body", body);
    }
    return attributes.size() == 0 ? null : attributes;
  }

  /**
   * Media type.
   *
   * @return Media type.
   */
  @JsonIgnore
  public Map<String, RamlType> getMediaType() {
    return mediaType;
  }

  /**
   * Set media type.
   *
   * @param mediaType Media type.
   * @param body RAML type.
   */
  public void setMediaType(final String mediaType, RamlType body) {
    if (this.mediaType == null) {
      this.mediaType = new LinkedHashMap<>();
    }
    this.mediaType.put(mediaType, body);
  }
}


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

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyException;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.List;

import javax.crypto.Cipher;
import javax.crypto.EncryptedPrivateKeyInfo;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSessionContext;
import javax.net.ssl.TrustManagerFactory;
import javax.security.auth.x500.X500Principal;

/**
 * A secure socket protocol implementation which acts as a factory for {@link SSLEngine} and
 * {@link SslHandler}.
 * Internally, it is implemented via JDK's {@link SSLContext} or OpenSSL's {@code SSL_CTX}.
 *
 *
Making your server support SSL/TLS

 *

 * // In your {@link ChannelInitializer}:
 * {@link ChannelPipeline} p = channel.pipeline();
 * {@link SslContext} sslCtx = {@link SslContextBuilder#forServer(File, File) SslContextBuilder.forServer(...)}.build();
 * p.addLast("ssl", {@link #newEngine(ByteBufAllocator) sslCtx.newEngine(channel.alloc())});
 * ...
 *

 *
 *
Making your client support SSL/TLS

 *

 * // In your {@link ChannelInitializer}:
 * {@link ChannelPipeline} p = channel.pipeline();
 * {@link SslContext} sslCtx = {@link SslContextBuilder#forClient() SslContextBuilder.forClient()}.build();
 * p.addLast("ssl", {@link #newEngine(ByteBufAllocator, String, int) sslCtx.newEngine(channel.alloc(), host, port)});
 * ...
 *

 *
 * Kindly Borrowed from Netty
 */
public abstract class SslContext {
  static final CertificateFactory X509_CERT_FACTORY;

  static {
    try {
      X509_CERT_FACTORY = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
      throw new IllegalStateException("unable to instance X.509 CertificateFactory", e);
    }
  }

  public static SslContext newServerContextInternal(
      final File trustCertChainFile,
      final File keyCertChainFile, final File keyFile, final String keyPassword,
      final long sessionCacheSize, final long sessionTimeout) throws SSLException {
    return new JdkSslServerContext(trustCertChainFile, keyCertChainFile,
        keyFile, keyPassword, sessionCacheSize, sessionTimeout);
  }

  /**
   * Returns the size of the cache used for storing SSL session objects.
   */
  public abstract long sessionCacheSize();

  public abstract long sessionTimeout();

  public abstract SSLContext context();

  /**
   * Returns the {@link SSLSessionContext} object held by this context.
   */
  public abstract SSLSessionContext sessionContext();

  /**
   * Generates a key specification for an (encrypted) private key.
   *
   * @param password characters, if {@code null} or empty an unencrypted key is assumed
   * @param key bytes of the DER encoded private key
   *
   * @return a key specification
   *
   * @throws IOException if parsing {@code key} fails
   * @throws NoSuchAlgorithmException if the algorithm used to encrypt {@code key} is unkown
   * @throws NoSuchPaddingException if the padding scheme specified in the decryption algorithm is
   *         unkown
   * @throws InvalidKeySpecException if the decryption key based on {@code password} cannot be
   *         generated
   * @throws InvalidKeyException if the decryption key based on {@code password} cannot be used to
   *         decrypt
   *         {@code key}
   * @throws InvalidAlgorithmParameterException if decryption algorithm parameters are somehow
   *         faulty
   */
  protected static PKCS8EncodedKeySpec generateKeySpec(final char[] password, final byte[] key)
      throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException,
      InvalidKeyException, InvalidAlgorithmParameterException {

    if (password == null || password.length == 0) {
      return new PKCS8EncodedKeySpec(key);
    }

    EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(key);
    SecretKeyFactory keyFactory = SecretKeyFactory
        .getInstance(encryptedPrivateKeyInfo.getAlgName());
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec);

    Cipher cipher = Cipher.getInstance(encryptedPrivateKeyInfo.getAlgName());
    cipher.init(Cipher.DECRYPT_MODE, pbeKey, encryptedPrivateKeyInfo.getAlgParameters());

    return encryptedPrivateKeyInfo.getKeySpec(cipher);
  }

  /**
   * Generates a new {@link KeyStore}.
   *
   * @param certChainFile a X.509 certificate chain file in PEM format,
   * @param keyFile a PKCS#8 private key file in PEM format,
   * @param keyPasswordChars the password of the {@code keyFile}.
   *        {@code null} if it's not password-protected.
   * @return generated {@link KeyStore}.
   */
  static KeyStore buildKeyStore(final File certChainFile, final File keyFile,
      final char[] keyPasswordChars)
          throws KeyStoreException, NoSuchAlgorithmException,
          NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException,
          CertificateException, KeyException, IOException {
    ByteBuffer encodedKeyBuf = PemReader.readPrivateKey(keyFile);
    byte[] encodedKey = encodedKeyBuf.array();

    PKCS8EncodedKeySpec encodedKeySpec = generateKeySpec(keyPasswordChars, encodedKey);

    PrivateKey key;
    try {
      key = KeyFactory.getInstance("RSA").generatePrivate(encodedKeySpec);
    } catch (InvalidKeySpecException ignore) {
      try {
        key = KeyFactory.getInstance("DSA").generatePrivate(encodedKeySpec);
      } catch (InvalidKeySpecException ignore2) {
        try {
          key = KeyFactory.getInstance("EC").generatePrivate(encodedKeySpec);
        } catch (InvalidKeySpecException e) {
          throw new InvalidKeySpecException("Neither RSA, DSA nor EC worked", e);
        }
      }
    }

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    List<ByteBuffer> certs = PemReader.readCertificates(certChainFile);
    List<Certificate> certChain = new ArrayList<Certificate>(certs.size());

    for (ByteBuffer buf : certs) {
      certChain.add(cf.generateCertificate(new ByteArrayInputStream(buf.array())));
    }

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    ks.setKeyEntry("key", key, keyPasswordChars,
        certChain.toArray(new Certificate[certChain.size()]));
    return ks;
  }

  /**
   * Build a {@link TrustManagerFactory} from a certificate chain file.
   *
   * @param certChainFile The certificate file to build from.
   * @param trustManagerFactory The existing {@link TrustManagerFactory} that will be used if not
   *        {@code null}.
   * @return A {@link TrustManagerFactory} which contains the certificates in {@code certChainFile}
   */
  protected static TrustManagerFactory buildTrustManagerFactory(final File certChainFile,
      TrustManagerFactory trustManagerFactory)
          throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException {
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    List<ByteBuffer> certs = PemReader.readCertificates(certChainFile);

    for (ByteBuffer buf : certs) {
      X509Certificate cert = (X509Certificate) cf
          .generateCertificate(new ByteArrayInputStream(buf.array()));
      X500Principal principal = cert.getSubjectX500Principal();
      ks.setCertificateEntry(principal.getName("RFC2253"), cert);
    }

    // Set up trust manager factory to use our key store.
    if (trustManagerFactory == null) {
      trustManagerFactory = TrustManagerFactory
          .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    }
    trustManagerFactory.init(ks);

    return trustManagerFactory;
  }
}