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

import com.google.inject.Binder;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import static java.util.Objects.requireNonNull;
import org.jooby.Deferred;
import org.jooby.Env;
import org.jooby.Route;
import org.jooby.exec.Exec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Completable;
import rx.Observable;
import rx.Scheduler;
import rx.Single;
import rx.Subscriber;
import rx.plugins.RxJavaPlugins;
import rx.plugins.RxJavaSchedulersHook;
import rx.schedulers.Schedulers;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;

/**
 *
rxjava

 *

 * Reactive programming via RxJava library.
 *

 *

 * RxJava is a Java VM implementation of Reactive Extensions: a
 * library for composing asynchronous and event-based programs by using observable sequences.
 *

 *
 *
exports

 *

 *
Route mapper that converts {@link Observable} (and family) into {@link Deferred} API.
 *

 *

 * manage the lifecycle of {@link Scheduler schedulers} and make sure they go down on application
 * shutdown time.
 *

 *

 *
 *
usage

 *
{@code
 * ...
 * import org.jooby.rx.Rx;
 * ...
 *
 * {
 *   use(new Rx());
 *
 *   get("/", req -> Observable.from("reactive programming in jooby!"));
 * }
 * }

 *
 *
how it works?

 *

 * Previous example is translated to:
 *

 *
{@code
 * {
 *   use(new Rx());
 *
 *   get("/", req -> {
 *
 *    return new Deferred(deferred -> {
 *      Observable.from("reactive programming in jooby!")
 *        .subscribe(deferred::resolve, deferred::reject);
 *    });
 *
 *   });
 * }
 * }

 *
 *

 * Translation is done via {@link Rx#rx()} route mapper. If you are a
 * rxjava programmer then you don't need to worry
 * for learning a new API and semantic. The {@link Rx#rx()} route mapper deal and take cares of
 * the {@link Deferred} API.
 *

 *
 *
rx mapper

 *

 * Advanced observable configuration is allowed via function adapter:
 *

 *
 *
{@code
 * ...
 * import org.jooby.rx.Rx;
 * ...
 *
 * {
 *   use(new Rx()
 *     .withObservable(observable -> observable.observeOn(Scheduler.io()),
 *     .withSingle(single -> single.observeOn(Scheduler.io()),
 *     .withCompletable(completable -> completable.observeOn(Scheduler.io()));
 *
 *   get("/observable", req -> Observable...);
 *
 *   get("/single", req -> Single...);
 *
 *   ....
 *
 *   get("/completable", req -> Completable...);
 *
 * }
 * }

 *
 *

 * Here every Observable/Single/Completable from a route handler will observe on the io
 * scheduler.
 *

 *
 *
schedulers

 *

 * This module provides the default {@link Scheduler} from
 * rxjava. But also let you define your own
 * {@link Scheduler scheduler} using the {@link Exec} module.
 *

 *
 *

 * rx.schedulers.io = forkjoin
 * rx.schedulers.computation = fixed
 * rx.schedulers.newThread = "fixed = 10"
 *

 *
 *

 * The previous example defines a:
 *

 *

 *
forkjoin pool for {@link Schedulers#io()}

 *
fixed thread pool equals to the number of available processors for
 * {@link Schedulers#computation()}

 *
fixed thread pool with a max of 10 for {@link Schedulers#newThread()}

 *

 *
 *

 * Of course, you can define/override all, some or none of them. In any case the {@link Scheduler}
 * will be shutdown at application shutdown time.
 *

 *
 * @author edgar
 * @since 1.0.0.CR3
 */
@SuppressWarnings("rawtypes")
public class Rx extends Exec {

  static class DeferredSubscriber extends Subscriber<Object> {

    private Deferred deferred;

    private final AtomicBoolean done = new AtomicBoolean(false);

    public DeferredSubscriber(final Deferred deferred) {
      this.deferred = deferred;
    }

    @Override
    public void onCompleted() {
      if (done.compareAndSet(false, true)) {
        deferred.resolve(null);
      }
      deferred = null;
    }

    @Override
    public void onError(final Throwable cause) {
      done.set(true);
      deferred.reject(cause);
    }

    @Override
    public void onNext(final Object value) {
      if (done.compareAndSet(false, true)) {
        deferred.resolve(value);
      }
    }
  }

  /** The logging system. */
  private final Logger log = LoggerFactory.getLogger(getClass());

  private Function<Observable, Observable> observable = Function.identity();

  private Function<Single, Single> single = Function.identity();

  private Function<Completable, Completable> completable = Function.identity();

  /**
   * Creates a new {@link Rx} module.
   */
  public Rx() {
    // daemon by default.
    daemon(true);
  }

  /**
   * Map a rx object like {@link Observable}, {@link Single} or {@link Completable} into a
   * {@link Deferred} object.
   *
   *
{@code
   * ...
   * import org.jooby.rx.Rx;
   * ...
   *
   * {
   *   with(() -> {
   *     get("/1", req -> Observable...);
   *
   *     get("/2", req -> Single...);
   *
   *     ....
   *
   *     get("/N", req -> Completable...);
   *
   *   }).map(Rx.rx());
   * }
   * }

   *
   * @return A new mapper.
   */
  public static Route.Mapper<Object> rx() {
    return rx(Function.identity(), Function.identity());
  }

  /**
   * Map a rx object like {@link Observable}, {@link Single} or {@link Completable} into a
   * {@link Deferred} object.
   *
   *
{@code
   * ...
   * import org.jooby.rx.Rx;
   * ...
   *
   * {
   *   use(new Rx());
   *
   *   with(() -> {
   *     get("/1", req -> Observable...);
   *
   *     get("/2", req -> Observable...);
   *
   *     ....
   *
   *     get("/N", req -> Observable...);
   *
   *   }).map(Rx.rx(
   *       observable -> observable.observeOn(Scheduler.io()),
   *       single -> single.observeOn(Scheduler.io()),
   *       completable -> completable.observeOn(Scheduler.io())));
   * }
   * }

   *
   * @param observable Observable adapter.
   * @param single Single adapter.
   * @return A new mapper.
   */
  public static Route.Mapper<Object> rx(final Function<Observable, Observable> observable,
    final Function<Single, Single> single) {
    return rx(observable, single, Function.identity());
  }

  /**
   * Map a rx object like {@link Observable}, {@link Single} or {@link Completable} into a
   * {@link Deferred} object.
   *
   *
{@code
   * ...
   * import org.jooby.rx.Rx;
   * ...
   *
   * {
   *   use(new Rx());
   *
   *   with(() -> {
   *     get("/1", req -> Observable...);
   *
   *     get("/2", req -> Observable...);
   *
   *     ....
   *
   *     get("/N", req -> Observable...);
   *
   *   }).map(Rx.rx(
   *       observable -> observable.observeOn(Scheduler.io()),
   *       single -> single.observeOn(Scheduler.io()),
   *       completable -> completable.observeOn(Scheduler.io())));
   * }
   * }

   *
   * @param observable Observable adapter.
   * @param single Single adapter.
   * @param completable Completable adapter.
   * @return A new mapper.
   */
  @SuppressWarnings("unchecked")
  public static Route.Mapper<Object> rx(final Function<Observable, Observable> observable,
    final Function<Single, Single> single, final Function<Completable, Completable> completable) {
    requireNonNull(observable, "Observable's adapter is required.");
    requireNonNull(single, "Single's adapter is required.");
    requireNonNull(completable, "Completable's adapter is required.");

    return Route.Mapper.create("rx", v -> {
      if (v instanceof Observable) {
        return new Deferred(
          deferred -> observable.apply((Observable) v).subscribe(new DeferredSubscriber(deferred)));
      } else if (v instanceof Single) {
        return new Deferred(
          deferred -> single.apply((Single) v).subscribe(new DeferredSubscriber(deferred)));
      } else if (v instanceof Completable) {
        return new Deferred(deferred -> completable.apply((Completable) v)
          .subscribe(new DeferredSubscriber(deferred)));
      }
      return v;
    });
  }

  /**
   * Apply the given function adapter to observables returned by routes:
   *
   *
{@code
   * {
   *   use(new Rx().withObservable(observable -> observable.observeOn(Schedulers.io())));
   *
   *   get("observable", -> {
   *     return Observable...
   *   });
   * }
   * }

   *
   * @param adapter Observable adapter.
   * @return This module.
   */
  public Rx withObservable(final Function<Observable, Observable> adapter) {
    this.observable = requireNonNull(adapter, "Observable's adapter is required.");
    return this;
  }

  /**
   * Apply the given function adapter to single returned by routes:
   *
   *
{@code
   * {
   *   use(new Rx().withSingle(observable -> observable.observeOn(Schedulers.io())));
   *
   *   get("single", -> {
   *     return Single...
   *   });
   * }
   * }

   *
   * @param adapter Single adapter.
   * @return This module.
   */
  public Rx withSingle(final Function<Single, Single> adapter) {
    this.single = requireNonNull(adapter, "Single's adapter is required.");
    return this;
  }

  /**
   * Apply the given function adapter to completable returned by routes:
   *
   *
{@code
   * {
   *   use(new Rx().withObservable(observable -> observable.observeOn(Schedulers.io())));
   *
   *   get("completable", -> {
   *     return Completable...
   *   });
   * }
   * }

   *
   * @param adapter Completable adapter.
   * @return This module.
   */
  public Rx withCompletable(final Function<Completable, Completable> adapter) {
    this.completable = requireNonNull(adapter, "Completable's adapter is required.");
    return this;
  }

  @Override
  public void configure(final Env env, final Config conf, final Binder binder) {
    // dump rx.* as system properties
    conf.getConfig("rx")
      .withoutPath("schedulers").entrySet()
      .forEach(
        e -> System.setProperty("rx." + e.getKey(), e.getValue().unwrapped().toString()));
    Map<String, Executor> executors = new HashMap<>();
    super.configure(env, conf, binder, executors::put);

    env.router()
      .map(rx(observable, single, completable));

    /**
     * Side effects of global/evil static state. Hack to turn off some of this errors.
     */
    trySchedulerHook(executors);

    // shutdown schedulers: silent shutdown in dev mode between app reloads
    env.onStop(() -> {
      try {
        Schedulers.shutdown();
      } catch (Throwable ex) {
        log.debug("Schedulers.shutdown() resulted in error", ex);
      }
    });
  }

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

  private void trySchedulerHook(final Map<String, Executor> executors) {
    RxJavaPlugins plugins = RxJavaPlugins.getInstance();
    try {
      plugins.registerSchedulersHook(new ExecSchedulerHook(executors));
    } catch (IllegalStateException ex) {
      // there is a scheduler hook already, check if ours and ignore the exception
      RxJavaSchedulersHook hook = plugins.getSchedulersHook();
      if (!(hook instanceof ExecSchedulerHook)) {
        throw ex;
      }
    }
  }

}


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

import java.util.Map;

import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.ResultSetFuture;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.SimpleStatement;
import com.datastax.driver.core.Statement;
import com.datastax.driver.mapping.Mapper;
import com.datastax.driver.mapping.MappingManager;
import com.datastax.driver.mapping.Result;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;

/**
 *
datastore

 *

 * Provides basic crud operations, like a {@link Mapper} without requiring an instance per each
 * entity class.
 *

 *
 * @author edgar
 * @since 1.0.0.CR7
 */
@SuppressWarnings({"rawtypes", "unchecked" })
public class Datastore {
  private final MappingManager manager;

  Datastore(final MappingManager manager) {
    this.manager = manager;
  }

  private <T> Mapper<T> mapper(final Class<T> entityClass) {
    return manager.mapper(entityClass);
  }

  /**
   * Fetch an entity based on its primary key.
   *
   * @param entityClass Entity class.
   * @param id Object id.
   * @return An entity or null.
   */
  public <T> T get(final Class<T> entityClass, final Object id) {
    return mapper(entityClass).get(id);
  }

  /**
   * Fetch an entity based on its primary key.
   *
   * @param entityClass Entity class.
   * @param id Object id.
   * @return A ListenableFuture containing an entity or null
   */
  public <T> ListenableFuture<T> getAsync(final Class<T> entityClass, final Object id) {
    return mapper(entityClass).getAsync(id);
  }

  /**
   * Delete an entity by ID.
   *
   * @param entityClass Entity class.
   * @param id entity ID.
   * @param options Options.
   */
  public void delete(final Class<?> entityClass, final Object id, final Mapper.Option... options) {
    Mapper mapper = mapper(entityClass);
    mapper.delete(id, options);
  }

  /**
   * Delete an entity by ID.
   *
   * @param entityClass Entity class.
   * @param id Entity id.
   * @param options Options.
   * @return An empty listenable future.
   */
  public ListenableFuture<Void> deleteAsync(final Class<?> entityClass, final Object id,
      final Mapper.Option... options) {
    Mapper mapper = mapper(entityClass);
    return mapper.deleteAsync(id, options);
  }

  /**
   * Delete an entity.
   *
   * @param entity Entity to delete.
   * @param options Options.
   */
  public void delete(final Object entity, final Mapper.Option... options) {
    Mapper mapper = mapper(entity.getClass());
    mapper.delete(entity, options);
  }

  /**
   * Delete an entity.
   *
   * @param entity Entity to delete.
   * @param options Options.
   * @return An empty listenable future.
   */
  public ListenableFuture<Void> deleteAsync(final Object entity, final Mapper.Option... options) {
    Mapper mapper = mapper(entity.getClass());
    return mapper.deleteAsync(entity, options);
  }

  /**
   * Save an entity.
   *
   * @param entity Entity to save.
   * @param options Options.
   */
  public <T> void save(final T entity, final Mapper.Option... options) {
    Class entityClass = entity.getClass();
    Mapper mapper = mapper(entityClass);
    mapper.save(entity, options);
  }

  /**
   * Save an entity.
   *
   * @param entity Entity to save.
   * @param options Options.
   * @return An empty listenable future.
   */
  public <T> ListenableFuture<Void> saveAsync(final T entity, final Mapper.Option... options) {
    Class entityClass = entity.getClass();
    Mapper mapper = mapper(entityClass);
    return mapper.saveAsync(entity, options);
  }

  /**
   * Execute a query and map result to entityClass.
   *
   * @param entityClass Entity class.
   * @param statement Statement to execute.
   * @param values Statement parameters.
   * @return A query result.
   */
  public <T> Result<T> query(final Class<T> entityClass, final String statement,
      final Map<String, Object> values) {
    return query(entityClass, new SimpleStatement(statement, values));
  }

  /**
   * Execute a query and map result to entityClass.
   *
   * @param entityClass Entity class.
   * @param statement Statement to execute.
   * @param values Statement parameters.
   * @return A query result.
   */
  public <T> Result<T> query(final Class<T> entityClass, final String statement,
      final Object... values) {
    return query(entityClass, new SimpleStatement(statement, values));
  }

  /**
   * Execute a query and map result to entityClass.
   *
   * @param entityClass Entity class.
   * @param statement Statement to execute.
   * @return A query result.
   */
  public <T> Result<T> query(final Class<T> entityClass, final Statement statement) {
    Mapper<T> mapper = mapper(entityClass);
    Session session = mapper.getManager().getSession();
    ResultSet rs = session.execute(statement);
    return mapper.map(rs);
  }

  /**
   * Execute a query and map result to entityClass.
   *
   * @param entityClass Entity class.
   * @param statement Statement to execute.
   * @param values Statement parameters.
   * @return A listenable future holding the result.
   */
  public <T> ListenableFuture<Result<T>> queryAsync(final Class<T> entityClass,
      final String statement, final Map<String, Object> values) {
    return queryAsync(entityClass, new SimpleStatement(statement, values));
  }

  /**
   * Execute a query and map result to entityClass.
   *
   * @param entityClass Entity class.
   * @param statement Statement to execute.
   * @param values Statement parameters.
   * @return A listenable future holding the result.
   */
  public <T> ListenableFuture<Result<T>> queryAsync(final Class<T> entityClass,
      final String statement, final Object... values) {
    return queryAsync(entityClass, new SimpleStatement(statement, values));
  }

  /**
   * Execute a query and map result to entityClass.
   *
   * @param entityClass Entity class.
   * @param statement Statement to execute.
   * @return A listenable future holding the result.
   */
  public <T> ListenableFuture<Result<T>> queryAsync(final Class<T> entityClass,
      final Statement statement) {
    Mapper<T> mapper = mapper(entityClass);
    Session session = mapper.getManager().getSession();
    ResultSetFuture rs = session.executeAsync(statement);
    return Futures.transformAsync(rs, rs1 -> Futures.immediateFuture(mapper.map(rs1)));
  }
}


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

/**
 * HTTP status codes.
 *
 *

 * This code has been kindly borrowed from Spring.
 *

 *
 * @author Arjen Poutsma
 * @see HTTP Status Code Registry
 * @see List of HTTP status codes -
 *      Wikipedia
 */
public class Status {

  private static final Map<Integer, Status> statusMap = new HashMap<>();

  // 1xx Informational

  /**
   * {@code 100 Continue}.
   *
   * @see HTTP/1.1
   */
  public static final Status CONTINUE = new Status(100, "Continue");
  /**
   * {@code 101 Switching Protocols}.
   *
   * @see HTTP/1.1
   */
  public static final Status SWITCHING_PROTOCOLS = new Status(101, "Switching Protocols");
  /**
   * {@code 102 Processing}.
   *
   * @see WebDAV
   */
  public static final Status PROCESSING = new Status(102, "Processing");
  /**
   * {@code 103 Checkpoint}.
   *
   * @see A proposal for
   *      supporting resumable POST/PUT HTTP requests in HTTP/1.0
   */
  public static final Status CHECKPOINT = new Status(103, "Checkpoint");

  // 2xx Success

  /**
   * {@code 200 OK}.
   *
   * @see HTTP/1.1
   */
  public static final Status OK = new Status(200, "Success");

  /**
   * {@code 201 Created}.
   *
   * @see HTTP/1.1
   */
  public static final Status CREATED = new Status(201, "Created");
  /**
   * {@code 202 Accepted}.
   *
   * @see HTTP/1.1
   */
  public static final Status ACCEPTED = new Status(202, "Accepted");
  /**
   * {@code 203 Non-Authoritative Information}.
   *
   * @see HTTP/1.1
   */
  public static final Status NON_AUTHORITATIVE_INFORMATION = new Status(203, "Non-Authoritative Information");
  /**
   * {@code 204 No Content}.
   *
   * @see HTTP/1.1
   */
  public static final Status NO_CONTENT = new Status(204, "No Content");
  /**
   * {@code 205 Reset Content}.
   *
   * @see HTTP/1.1
   */
  public static final Status RESET_CONTENT = new Status(205, "Reset Content");
  /**
   * {@code 206 Partial Content}.
   *
   * @see HTTP/1.1
   */
  public static final Status PARTIAL_CONTENT = new Status(206, "Partial Content");
  /**
   * {@code 207 Multi-Status}.
   *
   * @see WebDAV
   */
  public static final Status MULTI_STATUS = new Status(207, "Multi-Status");
  /**
   * {@code 208 Already Reported}.
   *
   * @see WebDAV Binding Extensions
   */
  public static final Status ALREADY_REPORTED = new Status(208, "Already Reported");
  /**
   * {@code 226 IM Used}.
   *
   * @see Delta encoding in HTTP
   */
  public static final Status IM_USED = new Status(226, "IM Used");

  // 3xx Redirection

  /**
   * {@code 300 Multiple Choices}.
   *
   * @see HTTP/1.1
   */
  public static final Status MULTIPLE_CHOICES = new Status(300, "Multiple Choices");
  /**
   * {@code 301 Moved Permanently}.
   *
   * @see HTTP/1.1
   */
  public static final Status MOVED_PERMANENTLY = new Status(301, "Moved Permanently");
  /**
   * {@code 302 Found}.
   *
   * @see HTTP/1.1
   */
  public static final Status FOUND = new Status(302, "Found");
  /**
   * {@code 303 See Other}.
   *
   * @see HTTP/1.1
   */
  public static final Status SEE_OTHER = new Status(303, "See Other");
  /**
   * {@code 304 Not Modified}.
   *
   * @see HTTP/1.1
   */
  public static final Status NOT_MODIFIED = new Status(304, "Not Modified");
  /**
   * {@code 305 Use Proxy}.
   *
   * @see HTTP/1.1
   */
  public static final Status USE_PROXY = new Status(305, "Use Proxy");
  /**
   * {@code 307 Temporary Redirect}.
   *
   * @see HTTP/1.1
   */
  public static final Status TEMPORARY_REDIRECT = new Status(307, "Temporary Redirect");
  /**
   * {@code 308 Resume Incomplete}.
   *
   * @see A proposal for
   *      supporting resumable POST/PUT HTTP requests in HTTP/1.0
   */
  public static final Status RESUME_INCOMPLETE = new Status(308, "Resume Incomplete");

  // --- 4xx Client Error ---

  /**
   * {@code 400 Bad Request}.
   *
   * @see HTTP/1.1
   */
  public static final Status BAD_REQUEST = new Status(400, "Bad Request");

  /**
   * {@code 401 Unauthorized}.
   *
   * @see HTTP/1.1
   */
  public static final Status UNAUTHORIZED = new Status(401, "Unauthorized");
  /**
   * {@code 402 Payment Required}.
   *
   * @see HTTP/1.1
   */
  public static final Status PAYMENT_REQUIRED = new Status(402, "Payment Required");
  /**
   * {@code 403 Forbidden}.
   *
   * @see HTTP/1.1
   */
  public static final Status FORBIDDEN = new Status(403, "Forbidden");
  /**
   * {@code 404 Not Found}.
   *
   * @see HTTP/1.1
   */
  public static final Status NOT_FOUND = new Status(404, "Not Found");
  /**
   * {@code 405 Method Not Allowed}.
   *
   * @see HTTP/1.1
   */
  public static final Status METHOD_NOT_ALLOWED = new Status(405, "Method Not Allowed");
  /**
   * {@code 406 Not Acceptable}.
   *
   * @see HTTP/1.1
   */
  public static final Status NOT_ACCEPTABLE = new Status(406, "Not Acceptable");
  /**
   * {@code 407 Proxy Authentication Required}.
   *
   * @see HTTP/1.1
   */
  public static final Status PROXY_AUTHENTICATION_REQUIRED = new Status(407, "Proxy Authentication Required");
  /**
   * {@code 408 Request Timeout}.
   *
   * @see HTTP/1.1
   */
  public static final Status REQUEST_TIMEOUT = new Status(408, "Request Timeout");
  /**
   * {@code 409 Conflict}.
   *
   * @see HTTP/1.1
   */
  public static final Status CONFLICT = new Status(409, "Conflict");
  /**
   * {@code 410 Gone}.
   *
   * @see HTTP/1.1
   */
  public static final Status GONE = new Status(410, "Gone");
  /**
   * {@code 411 Length Required}.
   *
   * @see HTTP/1.1
   */
  public static final Status LENGTH_REQUIRED = new Status(411, "Length Required");
  /**
   * {@code 412 Precondition failed}.
   *
   * @see HTTP/1.1
   */
  public static final Status PRECONDITION_FAILED = new Status(412, "Precondition Failed");
  /**
   * {@code 413 Request Entity Too Large}.
   *
   * @see HTTP/1.1
   */
  public static final Status REQUEST_ENTITY_TOO_LARGE = new Status(413, "Request Entity Too Large");
  /**
   * {@code 414 Request-URI Too Long}.
   *
   * @see HTTP/1.1
   */
  public static final Status REQUEST_URI_TOO_LONG = new Status(414, "Request-URI Too Long");
  /**
   * {@code 415 Unsupported Media Type}.
   *
   * @see HTTP/1.1
   */
  public static final Status UNSUPPORTED_MEDIA_TYPE = new Status(415, "Unsupported Media Type");
  /**
   * {@code 416 Requested Range Not Satisfiable}.
   *
   * @see HTTP/1.1
   */
  public static final Status REQUESTED_RANGE_NOT_SATISFIABLE = new Status(416, "Requested range not satisfiable");
  /**
   * {@code 417 Expectation Failed}.
   *
   * @see HTTP/1.1
   */
  public static final Status EXPECTATION_FAILED = new Status(417, "Expectation Failed");
  /**
   * {@code 418 I'm a teapot}.
   *
   * @see HTCPCP/1.0
   */
  public static final Status I_AM_A_TEAPOT = new Status(418, "I'm a teapot");
  /**
   * {@code 422 Unprocessable Entity}.
   *
   * @see WebDAV
   */
  public static final Status UNPROCESSABLE_ENTITY = new Status(422, "Unprocessable Entity");
  /**
   * {@code 423 Locked}.
   *
   * @see WebDAV
   */
  public static final Status LOCKED = new Status(423, "Locked");
  /**
   * {@code 424 Failed Dependency}.
   *
   * @see WebDAV
   */
  public static final Status FAILED_DEPENDENCY = new Status(424, "Failed Dependency");
  /**
   * {@code 426 Upgrade Required}.
   *
   * @see Upgrading to TLS Within
   *      HTTP/1.1
   */
  public static final Status UPGRADE_REQUIRED = new Status(426, "Upgrade Required");
  /**
   * {@code 428 Precondition Required}.
   *
   * @see Additional HTTP Status Codes
   */
  public static final Status PRECONDITION_REQUIRED = new Status(428, "Precondition Required");
  /**
   * {@code 429 Too Many Requests}.
   *
   * @see Additional HTTP Status Codes
   */
  public static final Status TOO_MANY_REQUESTS = new Status(429, "Too Many Requests");
  /**
   * {@code 431 Request Header Fields Too Large}.
   *
   * @see Additional HTTP Status Codes
   */
  public static final Status REQUEST_HEADER_FIELDS_TOO_LARGE = new Status(431, "Request Header Fields Too Large");

  // --- 5xx Server Error ---

  /**
   * {@code 500 Server Error}.
   *
   * @see HTTP/1.1
   */
  public static final Status SERVER_ERROR = new Status(500, "Server Error");
  /**
   * {@code 501 Not Implemented}.
   *
   * @see HTTP/1.1
   */
  public static final Status NOT_IMPLEMENTED = new Status(501, "Not Implemented");
  /**
   * {@code 502 Bad Gateway}.
   *
   * @see HTTP/1.1
   */
  public static final Status BAD_GATEWAY = new Status(502, "Bad Gateway");
  /**
   * {@code 503 Service Unavailable}.
   *
   * @see HTTP/1.1
   */
  public static final Status SERVICE_UNAVAILABLE = new Status(503, "Service Unavailable");
  /**
   * {@code 504 Gateway Timeout}.
   *
   * @see HTTP/1.1
   */
  public static final Status GATEWAY_TIMEOUT = new Status(504, "Gateway Timeout");
  /**
   * {@code 505 HTTP Version Not Supported}.
   *
   * @see HTTP/1.1
   */
  public static final Status HTTP_VERSION_NOT_SUPPORTED = new Status(505, "HTTP Version not supported");
  /**
   * {@code 506 Variant Also Negotiates}
   *
   * @see Transparent Content
   *      Negotiation
   */
  public static final Status VARIANT_ALSO_NEGOTIATES = new Status(506, "Variant Also Negotiates");
  /**
   * {@code 507 Insufficient Storage}
   *
   * @see WebDAV
   */
  public static final Status INSUFFICIENT_STORAGE = new Status(507, "Insufficient Storage");
  /**
   * {@code 508 Loop Detected}
   *
   * @see WebDAV Binding Extensions
   */
  public static final Status LOOP_DETECTED = new Status(508, "Loop Detected");
  /**
   * {@code 509 Bandwidth Limit Exceeded}
   */
  public static final Status BANDWIDTH_LIMIT_EXCEEDED = new Status(509, "Bandwidth Limit Exceeded");
  /**
   * {@code 510 Not Extended}
   *
   * @see HTTP Extension Framework
   */
  public static final Status NOT_EXTENDED = new Status(510, "Not Extended");
  /**
   * {@code 511 Network Authentication Required}.
   *
   * @see Additional HTTP Status Codes
   */
  public static final Status NETWORK_AUTHENTICATION_REQUIRED = new Status(511, "Network Authentication Required");

  private final int value;

  private final String reason;

  private Status(final int value, final String reason) {
    statusMap.put(Integer.valueOf(value), this);
    this.value = value;
    this.reason = reason;
  }

  /**
   * @return Return the integer value of this status code.
   */
  public int value() {
    return this.value;
  }

  /**
   * @return True, for status code >= 400.
   */
  public boolean isError() {
    return this.value >= 400;
  }

  /**
   * @return the reason phrase of this status code.
   */
  public String reason() {
    return reason;
  }

  /**
   * Return a string representation of this status code.
   */
  @Override
  public String toString() {
    return reason() + " (" + value + ")";
  }

  /**
   * Return the enum constant of this type with the specified numeric value.
   *
   * @param statusCode the numeric value of the enum to be returned
   * @return the enum constant with the specified numeric value
   * @throws IllegalArgumentException if this enum has no constant for the specified numeric value
   */
  public static Status valueOf(final int statusCode) {
    Integer key = Integer.valueOf(statusCode);
    Status status = statusMap.get(key);
    return status == null? new Status(key, key.toString()) : 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.internal.netty;

import static io.netty.channel.ChannelFutureListener.CLOSE;
import static java.util.Objects.requireNonNull;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

import io.netty.handler.codec.http.websocketx.*;
import org.jooby.WebSocket;
import org.jooby.WebSocket.OnError;
import org.jooby.WebSocket.SuccessCallback;
import org.jooby.spi.NativeWebSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelConfig;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

public class NettyWebSocket implements NativeWebSocket {

  public static final AttributeKey<NettyWebSocket> KEY = AttributeKey
      .newInstance(NettyWebSocket.class.getName());

  /** The logging system. */
  private final Logger log = LoggerFactory.getLogger(getClass());

  private ChannelHandlerContext ctx;

  private Consumer<NettyWebSocket> handshake;

  private Runnable onConnectCallback;

  private WebSocketServerHandshaker handshaker;

  private Consumer<String> onTextCallback;

  private Consumer<ByteBuffer> onBinaryCallback;

  private BiConsumer<Integer, Optional<String>> onCloseCallback;

  private Consumer<Throwable> onErrorCallback;

  private final CountDownLatch ready = new CountDownLatch(1);

  private ByteBuf buffer = null;

  private boolean bufferIsText = false;

  public NettyWebSocket(final ChannelHandlerContext ctx,
      final WebSocketServerHandshaker handshaker, final Consumer<NettyWebSocket> handshake) {
    this.ctx = ctx;
    this.handshaker = handshaker;
    this.handshake = handshake;
  }

  @Override
  public void close(final int status, final String reason) {
    handshaker.close(ctx.channel(), new CloseWebSocketFrame(status, reason))
        .addListener(CLOSE);
    Attribute<NettyWebSocket> ws = ctx.channel().attr(KEY);
    if (ws != null) {
      ws.set(null);
    }
  }

  @Override
  public void resume() {
    ChannelConfig config = ctx.channel().config();
    if (!config.isAutoRead()) {
      config.setAutoRead(true);
    }
  }

  @Override
  public void onConnect(final Runnable callback) {
    this.onConnectCallback = requireNonNull(callback, "A callback is required.");
  }

  @Override
  public void onTextMessage(final Consumer<String> callback) {
    this.onTextCallback = requireNonNull(callback, "A callback is required.");
  }

  @Override
  public void onBinaryMessage(final Consumer<ByteBuffer> callback) {
    this.onBinaryCallback = requireNonNull(callback, "A callback is required.");
  }

  @Override
  public void onCloseMessage(final BiConsumer<Integer, Optional<String>> callback) {
    this.onCloseCallback = requireNonNull(callback, "A callback is required.");
  }

  @Override
  public void onErrorMessage(final Consumer<Throwable> callback) {
    this.onErrorCallback = requireNonNull(callback, "A callback is required.");
  }

  @Override
  public void pause() {
    ChannelConfig config = ctx.channel().config();
    if (config.isAutoRead()) {
      config.setAutoRead(false);
    }
  }

  @Override
  public void terminate() throws IOException {
    this.onCloseCallback.accept(1006, Optional.of("Harsh disconnect"));
    ctx.disconnect().addListener(CLOSE);
  }

  @Override
  public void sendBytes(final ByteBuffer data, final SuccessCallback success, final OnError err) {
    sendBytes(Unpooled.wrappedBuffer(data), success, err);
  }

  @Override
  public void sendBytes(final byte[] data, final SuccessCallback success, final OnError err) {
    sendBytes(Unpooled.wrappedBuffer(data), success, err);
  }

  @Override
  public void sendText(final String data, final SuccessCallback success, final OnError err) {
    ctx.channel().writeAndFlush(new TextWebSocketFrame(data))
        .addListener(listener(success, err));
  }

  @Override
  public void sendText(final ByteBuffer data, final SuccessCallback success, final OnError err) {
    ByteBuf buffer = Unpooled.wrappedBuffer(data);
    ctx.channel().writeAndFlush(new TextWebSocketFrame(buffer))
        .addListener(listener(success, err));
  }

  @Override
  public void sendText(final byte[] data, final SuccessCallback success, final OnError err) {
    ByteBuf buffer = Unpooled.wrappedBuffer(data);
    ctx.channel().writeAndFlush(new TextWebSocketFrame(buffer))
        .addListener(listener(success, err));
  }

  @Override
  public boolean isOpen() {
    return ctx.channel().isOpen();
  }

  public void connect() {
    onConnectCallback.run();
    ready.countDown();
  }

  public void hankshake() {
    handshake.accept(this);
  }

  public void handle(final Object msg) {
    ready();
    if (msg instanceof TextWebSocketFrame || msg instanceof BinaryWebSocketFrame || msg instanceof ContinuationWebSocketFrame){
      handleWebsocketMessage((WebSocketFrame) msg);
    } else if (msg instanceof CloseWebSocketFrame) {
      CloseWebSocketFrame closeFrame = ((CloseWebSocketFrame) msg).retain();
      int statusCode = closeFrame.statusCode();
      onCloseCallback.accept(statusCode == -1 ? WebSocket.NORMAL.code() : statusCode,
          Optional.ofNullable(closeFrame.reasonText()));
      handshaker.close(ctx.channel(), closeFrame).addListener(CLOSE);
    } else if (msg instanceof Throwable) {
      onErrorCallback.accept((Throwable) msg);
    }
  }

  private void handleWebsocketMessage(WebSocketFrame webSocketMessage) {
    if (!webSocketMessage.isFinalFragment()) {
      if (this.buffer == null) {
        if (webSocketMessage instanceof ContinuationWebSocketFrame){
          throw new IllegalStateException("Received ContinuationWebSocketFrame as a first frame of a message.");
        }
        this.buffer = Unpooled.copiedBuffer(webSocketMessage.content());
        this.bufferIsText = webSocketMessage instanceof TextWebSocketFrame;
      } else {
        this.buffer.writeBytes(webSocketMessage.content());
      }
    } else {
      if (this.buffer != null) {
        this.buffer.writeBytes(webSocketMessage.content());
        try{
          if (this.bufferIsText) {
            onTextCallback.accept(this.buffer.toString(StandardCharsets.UTF_8));
          } else {
            onBinaryCallback.accept(this.buffer.nioBuffer());
          }
        } finally {
          this.buffer = null;
        }
      } else {
        // shortcut to avoid allocating unnecessary copiedBuffers
        if (webSocketMessage instanceof TextWebSocketFrame) {
          onTextCallback.accept(((TextWebSocketFrame) webSocketMessage).text());
        } else if (webSocketMessage instanceof BinaryWebSocketFrame) {
          onBinaryCallback.accept(webSocketMessage.content().nioBuffer());
        }
      }
    }
  }

  /**
   * Make sure hankshake/connect is set.
   */
  private void ready() {
    try {
      ready.await();
    } catch (InterruptedException ex) {
      log.error("Connect call was inturrupted", ex);
      Thread.currentThread().interrupt();
    }
  }

  private void sendBytes(final ByteBuf buffer, final SuccessCallback success, final OnError err) {
    ctx.channel().writeAndFlush(new BinaryWebSocketFrame(buffer))
        .addListener(listener(success, err));
  }

  private GenericFutureListener<? extends Future<? super Void>> listener(
      final SuccessCallback success, final OnError err) {
    return f -> {
      if (f.isSuccess()) {
        success.invoke();
      } else {
        err.onError(f.cause());
      }
    };
  }

}


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

import static java.util.Objects.requireNonNull;

import java.util.Properties;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

import org.jooby.Env;
import org.jooby.Jooby.Module;

import com.google.inject.Binder;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;

/**
 *
hazelcast module

 *

 * Exports a Hazelcast instances and optionally a
 * {@link HcastSessionStore} session store.
 *

 *
 *
usage

 *
 *

 * {
 *   use(new Hcast());
 *
 *   get("/:key", req {@literal ->} {
 *     HazelcastInstance hcast = req.require(HazelcastInstance.class);
 *     ...
 *   });
 * }
 *

 *
 *
configuration

 *

 * Any property under hazelcast.* will be automatically add it while bootstrapping a
 * {@link HazelcastInstance}.
 *

 *
 *

 * Configuration can be done programmatically via: {@link #doWith(Consumer)}.
 *

 *
 *

 * {
 *   use(new Hcast()
 *    .doWith(config {@literal ->} {
 *      config.setXxx
 *    })
 *   );
 * }
 *

 *
 * @author edgar
 * @since 0.9.0
 */
public class Hcast implements Module {

  private BiConsumer<com.hazelcast.config.Config, Config> configurer;

  /**
   * Set a configurer callback.
   *
   * @param configurer A configurer callback.
   * @return This instance.
   */
  public Hcast doWith(final BiConsumer<com.hazelcast.config.Config, Config> configurer) {
    this.configurer = requireNonNull(configurer, "Configurer callback is required.");
    return this;
  }

  /**
   * Set a configurer callback.
   *
   * @param configurer A configurer callback.
   * @return This instance.
   */
  public Hcast doWith(final Consumer<com.hazelcast.config.Config> configurer) {
    requireNonNull(configurer, "Configurer callback is required.");
    return doWith((config, conf) -> configurer.accept(config));
  }

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

    config.setProperties(toProperties(conf.getConfig("hazelcast")));

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

    HazelcastInstance hcast = Hazelcast.newHazelcastInstance(config);

    binder.bind(com.hazelcast.config.Config.class).toInstance(config);
    binder.bind(HazelcastInstance.class).toInstance(hcast);
    env.onStop(hcast::shutdown);
  }

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

  private Properties toProperties(final Config config) {
    Properties properties = new Properties();

    config.withoutPath("session").entrySet().forEach(prop -> properties.setProperty("hazelcast." + prop.getKey(), prop.getValue().unwrapped().toString()));

    return properties;
  }

}