/**
 *                                  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.debugrmational 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.debugrmation. (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.assets;

import com.google.common.base.CaseFormat;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.ByteStreams;
import com.google.common.io.Closeables;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigValue;
import static java.util.Objects.requireNonNull;
import org.jooby.MediaType;
import org.jooby.funzy.Try;
import org.jooby.internal.assets.AssetWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 *
Asset compiler

 *

 * Process static files by validate or modify them in some way.
 *

 *
 * @author edgar
 * @see AssetProcessor
 * @see Assets
 * @since 0.11.0
 */
public class AssetCompiler {

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

  private final Map<String, List<AssetProcessor>> pipeline;

  private final List<AssetAggregator> aggregators = new ArrayList<>();

  private final Map<String, List<String>> fileset;

  private final Predicate<String> scripts;

  private final Predicate<String> styles;

  private final Config conf;

  private final Charset charset;

  private final EngineFactory engineFactory;

  private ClassLoader loader;

  private BiConsumer<Integer, Integer> progress;

  public AssetCompiler(final Config conf) throws Exception {
    this(AssetClassLoader.classLoader(conf.getClass().getClassLoader()), conf);
  }

  public AssetCompiler(final ClassLoader loader, final Config conf) throws Exception {
    this.loader = loader;
    this.conf = requireNonNull(conf, "Assets conf is required.");
    String basedir = conf.hasPath("assets.basedir") ? spath(conf.getString("assets.basedir")) : "";
    this.charset = Charset.forName(this.conf.getString("assets.charset"));
    this.engineFactory = engineFactory(loader);
    if (this.conf.hasPath("assets.fileset")) {
      this.fileset = fileset(this.loader, engineFactory, basedir, this.conf, aggregators::add);
    } else {
      this.fileset = new HashMap<>();
    }
    this.scripts = predicate(this.conf, ".js", ".coffee", ".ts");
    this.styles = predicate(this.conf, ".css", ".scss", ".sass", ".less");
    if (this.fileset.size() > 0) {
      this.pipeline = pipeline(this.loader, engineFactory, this.conf.getConfig("assets"));
    } else {
      this.pipeline = Collections.emptyMap();
    }
  }

  /**
   * Get all the assets for the provided file set. Example:
   *
   *

   * assets {
   *   fileset {
   *     home: [home.css, home.js]
   *   }
   * }
   *

   *
   * This method returns home.css and home.js for home file
   * set. If there is no fileset under that name then it returns an empty list.
   *
   * @param name Fileset name.
   * @return List of files or empty list.
   */
  public List<String> assets(final String name) {
    return fileset.getOrDefault(name, Collections.emptyList());
  }

  /**
   * @return Returns all the fileset.
   */
  public Set<String> fileset() {
    return fileset.keySet();
  }

  /**
   * Iterate over fileset and common path pattern for them. Example:
   *
   *

   * {
   *   assets {
   *     fileset {
   *       lib: [js/lib/jquery.js],
   *       home: [css/style.css, js/home.js]
   *     }
   *   }
   * }
   *

   *
   * This method returns a set with /css/** and /js/** pattern.
   *
   * @return Path pattern of the entire fileset.
   */
  public Set<String> patterns() {
    return patterns(file -> aggregators.stream()
        .noneMatch(it -> it.fileset().contains(file)))
        .map(v -> "/" + v + "/**")
        .collect(Collectors.toCollection(LinkedHashSet::new));
  }

  /**
   * Get all the javascript (or derived) for the provided fileset. Example:
   *
   *

   * {
   *   assets {
   *     fileset {
   *       mypage: [mypage.js, mypage.css]
   *     }
   *   }
   * }
   *

   *
   *

   * This method returns mypage.js for mypage fileset.
   *

   *
   * @param fileset Fileset name.
   * @return All the scripts for a fileset.
   */
  public List<String> scripts(final String fileset) {
    return assets(fileset)
        .stream()
        .filter(scripts)
        .collect(Collectors.toList());
  }

  /**
   * Get all the css files (or derived) for the provided fileset. Example:
   *
   *

   * {
   *   assets {
   *     fileset {
   *       mypage: [mypage.js, mypage.css]
   *     }
   *   }
   * }
   *

   *
   *

   * This method returns mypage.js for mypage fileset.
   *

   *
   * @param fileset Fileset name.
   * @return All the scripts for a fileset.
   */
  public List<String> styles(final String fileset) {
    return assets(fileset)
        .stream()
        .filter(styles)
        .collect(Collectors.toList());
  }

  /**
   * List all the {@link AssetProcessor} for a distribution (a.k.a. environment).
   *
   * @param dist Distribution's name.
   * @return A readonly list of available {@link AssetProcessor}.
   */
  public List<AssetProcessor> pipeline(final String dist) {
    List<AssetProcessor> chain = this.pipeline.get(dist);
    if (chain == null) {
      log.debug("no pipeline for: {}", dist);
      return Collections.emptyList();
    }
    return Collections.unmodifiableList(chain);
  }

  /**
   * @return Readonly list of available {@link AssetAggregator}.
   */
  public List<AssetAggregator> aggregators() {
    return Collections.unmodifiableList(aggregators);
  }

  /**
   * Build assets using the given distribution and write output to the provided directory.
   *
   * Build process is defined as follow:
   *
   * 1. First, it runs all the aggregators (if any)
   * 2. Then iterates each fileset and per each file in the fileset it apply the processor pipeline.
   * 3. Finally, it merge all the files into one file and compressed/optimized if need it.
   *
   * @param dist Distribution's name (usually dev or dist).
   * @param dir Output directory.
   * @return Map with fileset name as key and list of generated assets.
   * @throws Exception If something goes wrong.
   */
  public Map<String, List<File>> build(final String dist, final File dir) throws Exception {
    log.debug("{} aggregators: {}", dist, aggregators);
    aggregators(aggregators, conf);

    return buildInternal(dist, dir);
  }

  private Map<String, List<File>> buildInternal(final String dist, final File dir)
      throws Exception {
    Map<String, List<File>> output = new LinkedHashMap<>();

    List<AssetProcessor> pipeline = pipeline(dist);

    Set<String> processed = new HashSet<>();
    Predicate<String> shouldProcess = dist.equals("dev") ? processed::add : path -> true;

    int total = fileset.values().stream()
        .mapToInt(List::size)
        .sum();
    int count = 0;
    log.debug("{} pipeline: {}", dist, pipeline);
    for (Entry<String, List<String>> entries : fileset.entrySet()) {
      String fset = entries.getKey();
      List<String> files = entries.getValue();

      log.debug("compiling {}:", fset);

      /** CSS: */
      AssetWriter css = new AssetWriter(dist, fset, dir, ".css", "", charset, this.fileset, styles);
      count += compile(pipeline, files.stream().filter(styles).iterator(), MediaType.css, css,
          shouldProcess, count, total);
      List<File> result = new ArrayList<>(css.getResult());

      /** JavaScript: */
      AssetWriter js = new AssetWriter(dist, fset, dir, ".js", ";", charset, this.fileset, scripts);
      count += compile(pipeline, files.stream().filter(scripts).iterator(), MediaType.js, js,
          shouldProcess, count, total);
      result.addAll(js.getResult());

      result.forEach(
          it -> log.debug("{} {} ({})", it.getName(), humanReadableByteCount(it.length()), it));
      output.put(fset, result);
    }
    return output;
  }

  private void aggregators(final List<AssetAggregator> aggregators, final Config conf)
      throws Exception {
    for (AssetAggregator it : aggregators) {
      log.debug("applying {}", it);
      it.run(conf);
    }

  }

  /**
   * Apply the processor pipeline to the given asset. Like {@link #build(String, File)} but for a
   * single file or asset.
   *
   * @param filename Asset to build.
   * @return Processed asset.
   * @throws Exception If something goes wrong.
   */
  public File buildOne(String filename, File dir) throws Exception {

    String dist = "dev";
    final MediaType type;
    AssetWriter writer;
    if (scripts.test(filename)) {
      type = MediaType.js;
      writer = new AssetWriter(dist, null, dir, ".js", ";", charset, this.fileset, scripts);
    } else if (styles.test(filename)) {
      type = MediaType.css;
      writer = new AssetWriter(dist, null, dir, ".css", "", charset, this.fileset, styles);
    } else {
      return null;
    }

    List<AssetProcessor> pipeline = pipeline(dist);
    compile(pipeline, ImmutableList.of(filename).iterator(), type, writer, path -> true, 0, 0);

    return new File(dir, filename);
  }

  /**
   * Print a summary of the given results.
   *
   * @param result Compilation result.
   * @param outDir Output directory.
   * @param dist Distribution (dev or prod).
   * @param duration Execution time in millis.
   * @param extraInfo Additional information.
   * @return Summary.
   */
  public String summary(Map<String, List<File>> result, Path outDir, String dist, long duration,
      String... extraInfo) {
    StringBuilder buffer = new StringBuilder();

    buffer.append("Summary:\n");
    long seconds = Duration.ofMillis(duration).getSeconds();
    String took = seconds > 0 ? seconds + "s" : duration + "ms";
    buffer.append("Pipeline: ").append(pipeline(dist)).append("\n");
    buffer.append("Time: ").append(took).append("\n");
    buffer.append("Output: ").append(outDir).append("\n");
    Stream.of(extraInfo).forEach(line -> buffer.append(line).append("\n"));
    int w1 = result.keySet().stream()
        .map(it -> it.length() + 2)
        .max(Integer::compareTo)
        .orElse(0);
    int mw1 = Math.max(w1, "Fileset".length() + 2);
    int w2 = result.values().stream()
        .flatMap(List::stream)
        .map(file -> outDir.relativize(file.toPath()).toString())
        .map(String::length)
        .max(Integer::compareTo)
        .orElse(0);
    buffer.append(format(w1, w2, "Fileset", "Output", "Size"));
    result.forEach((fileset, files) -> {
      if (files.size() > 0) {
        // Head
        buffer.append(format(mw1, w2, "  " + fileset, "", ""));
        // Tail
        files.forEach(file -> buffer.append(format(mw1, w2, "", outDir.relativize(file.toPath()),
            AssetCompiler.humanReadableByteCount(file.length()))));
      }
    });
    return buffer.toString();
  }

  private static String format(int w1, int w2, Object... args) {
    return String.format("%-" + w1 + "s %" + w2 + "s %10s\n", args);
  }

  @Override
  public String toString() {
    return fileset.toString();
  }

  public void stop() {
    if (engineFactory != null) {
      this.engineFactory.release();
    }
  }

  /**
   * Set a progress bar.
   *
   * @param progress Progress bar.
   */
  public void setProgressBar(BiConsumer<Integer, Integer> progress) {
    this.progress = progress;
  }

  private Stream<String> patterns(final Predicate<String> filter) {
    return fileset.values().stream()
        .flatMap(List::stream)
        .filter(filter)
        .map(path -> path.split("/")[1]);

  }

  private int compile(final List<AssetProcessor> pipeline, final Iterator<String> files,
      final MediaType type, final AssetWriter writer, Predicate<String> process, int progress,
      int total)
      throws Exception {
    int count = 0;
    while (files.hasNext()) {
      String file = files.next();
      if (process.test(file)) {
        String chunk = compile(pipeline, file, type, readFile(loader, file, charset));
        writer.write(file, chunk);
      } else {
        writer.add(file);
      }
      count += 1;
      if (this.progress != null) {
        this.progress.accept(progress + count, total);
      }
    }
    return count;
  }

  private String compile(final List<AssetProcessor> pipeline, final String filename,
      final MediaType type, final String input) throws Exception {

    log.debug("  {}", filename);
    Iterator<AssetProcessor> it = pipeline.iterator();
    String output = input;
    while (it.hasNext()) {
      AssetProcessor processor = it.next();
      if (processor.matches(type) && !processor.excludes(filename)) {
        String pname = processor.name();
        long start = System.currentTimeMillis();
        try {
          log.debug("    executing: {}", pname);
          output = processor.process(filename, output, conf, loader);
        } finally {
          long end = System.currentTimeMillis();
          log.debug("    {} took {}ms", pname, end - start);
        }
      }
    }
    return output;
  }

  private static String readFile(final ClassLoader loader, final String path, final Charset charset)
      throws IOException {
    String spath = path.startsWith("/") ? path.substring(1) : path;
    InputStream resource = loader.getResourceAsStream(spath);
    if (resource == null) {
      throw new FileNotFoundException(path);
    }
    return toString(resource, charset);
  }

  private static String toString(final InputStream in, final Charset charset) throws IOException {
    try {
      return new String(ByteStreams.toByteArray(in), charset);
    } finally {
      Closeables.closeQuietly(in);
    }
  }

  private static Predicate<String> predicate(final Config fileset, final String... extension) {
    String path = "assets" + extension[0];
    Set<String> extensions = new HashSet<>(Arrays.asList(extension));
    if (fileset.hasPath(path)) {
      extensions.addAll(strlist(fileset.getAnyRef(path)));
    }
    return file -> {
      for (String ext : extensions) {
        if (file.endsWith(ext)) {
          return true;
        }
      }
      return false;
    };
  }

  private static Map<String, List<String>> fileset(final ClassLoader loader,
      final EngineFactory engineFactory, final String basedir,
      final Config conf, final Consumer<AssetAggregator> aggregators) {
    Map<String, List<String>> raw = new HashMap<>();
    Map<String, List<String>> graph = new HashMap<>();
    Config assetconf = conf.getConfig("assets");
    Config fileset = assetconf.getConfig("fileset");
    // 1st pass, collect single resources (no merge)
    fileset.entrySet().forEach(e -> {
      List<String> key = Splitter.on('<')
          .trimResults()
          .omitEmptyStrings()
          .splitToList(unquote(e.getKey()));
      List<String> candidates = strlist(e.getValue().unwrapped(), v -> basedir + spath(v));
      List<String> values = new ArrayList<>();
      candidates.forEach(it -> Try.run(() -> processors(assetconf, loader, engineFactory, null, ImmutableList.of(it.substring(1)),
          ImmutableSet.of())
          .stream()
          .filter(AssetAggregator.class::isInstance)
          .forEach(p -> {
            AssetAggregator a = (AssetAggregator) p;
            aggregators.accept(a);
            a.fileset().forEach(f -> values.add(spath(f)));
          })).onFailure(x -> values.add(it)));
      raw.put(key.get(0), values);
      graph.put(key.get(0), key);
    });

    Map<String, List<String>> resolved = new HashMap<>();
    graph.forEach((fs, deps) -> resolve(fs, deps, raw, graph, resolved));
    return resolved;
  }

  private static List<String> resolve(final String fs, final List<String> deps,
      final Map<String, List<String>> raw, final Map<String, List<String>> graph,
      final Map<String, List<String>> resolved) {
    List<String> result = resolved.get(fs);
    if (result == null) {
      result = new ArrayList<>();
      resolved.put(fs, result);
      for (int i = deps.size() - 1; i > 0; i--) {
        result.addAll(resolve(deps.get(i), graph.get(deps.get(i)), raw, graph, resolved));
      }
      result.addAll(raw.get(fs));
    }
    return result;
  }

  private static String unquote(final String key) {
    return key.replace("\"", "");
  }

  private static Map<String, List<AssetProcessor>> pipeline(final ClassLoader loader,
      final EngineFactory engineFactory,
      final Config conf) throws Exception {
    Map<String, List<AssetProcessor>> processors = new HashMap<>();
    processors.put("dev", Collections.emptyList());
    if (conf.hasPath("pipeline")) {
      Set<String> filter = conf.getConfig("pipeline").entrySet().stream()
          .map(Entry::getKey)
          .collect(Collectors.toSet());
      filter.add("class");
      Set<Entry<String, ConfigValue>> entrySet = conf.getConfig("pipeline").entrySet();
      for (Entry<String, ConfigValue> entry : entrySet) {
        String env = unquote(entry.getKey());
        processors.put(env,
            processors(conf, loader, engineFactory, env, strlist(entry.getValue().unwrapped()),
                filter));
      }
    }
    return processors;
  }

  @SuppressWarnings("unchecked")
  private static <T extends AssetOptions> List<T> processors(final Config conf,
      final ClassLoader loader, final EngineFactory engineFactory, final String env,
      final List<String> names,
      final Set<String> filter) throws Exception {
    Map<String, Class<AssetOptions>> classes = new LinkedHashMap<>();
    for (Entry<String, String> entry : bind(conf, names).entrySet()) {
      classes.put(entry.getKey(), (Class<AssetOptions>) loader.loadClass(entry.getValue()));
    }
    return (List<T>) processors(conf, loader, engineFactory, env, filter, classes);
  }

  @SuppressWarnings("unchecked")
  private static <T extends AssetOptions> List<T> processors(final Config conf,
      final ClassLoader loader, final EngineFactory engineFactory, final String env,
      final Set<String>
          filter, final Map<String, Class<T>> classes) throws Exception {
    List<T> processors = new ArrayList<>();
    Function<Config, Config> without = options -> {
      for (String path : filter) {
        options = options.withoutPath(path);
      }
      return options;
    };
    for (Entry<String, Class<T>> entry : classes.entrySet()) {
      String name = entry.getKey();
      Class<T> clazz = entry.getValue();
      Config options = ConfigFactory.empty();
      if (conf.hasPath(name)) {
        options = conf.getConfig(name);
        if (env != null && options.hasPath(env)) {
          options = options.getConfig(env).withFallback(options);
        }
      }
      AssetOptions processor = clazz.newInstance();
      processor.set(without.apply(options));
      processors.add((T) processor);
      if (processor instanceof AssetProcessor) {
        ((AssetProcessor) processor).set(engineFactory);
      }
    }
    return processors;
  }

  private static EngineFactory engineFactory(ClassLoader loader) throws Exception {
    try {
      return (EngineFactory) loader
          .loadClass(System.getProperty("assets.engine", "org.jooby.assets.V8EngineFactory"))
          .newInstance();
    } catch (ClassNotFoundException e) {
      // Ignore:
      return null;
    }
  }

  private static Map<String, String> bind(final Config conf, final List<String> names) {
    Map<String, String> map = new LinkedHashMap<>();
    names.forEach(name -> {
      String clazz = AssetCompiler.class.getPackage().getName() + "."
          + CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, name);
      if (conf.hasPath(name + ".class")) {
        clazz = conf.getString(name + ".class");
      }
      map.put(name, clazz);
    });

    return map;
  }

  private static List<String> strlist(final Object value) {
    return strlist(value, v -> v);
  }

  @SuppressWarnings("unchecked")
  private static List<String> strlist(final Object value, final Function<String, String> mapper) {
    ImmutableList.Builder<String> list = ImmutableList.builder();
    if (value instanceof Collection) {
      ((Collection<? extends String>) value).forEach(v -> list.add(mapper.apply(v)));
    } else {
      list.add(mapper.apply(value.toString()));
    }
    return list.build();
  }

  private static String spath(final String path) {
    return path.charAt(0) == '/' ? path : "/" + path;
  }

  // http://stackoverflow.com/questions/3758606/how-to-convert-byte-size-into-human-readable-format-in-java
  static String humanReadableByteCount(final long bytes) {
    int unit = 1024;
    if (bytes < unit) {
      return bytes + "b";
    }
    int exp = (int) (Math.log(bytes) / Math.log(unit));
    char pre = "kmgtpe".charAt(exp - 1);
    return String.format("%.1f%sb", bytes / Math.pow(unit, exp), pre);
  }

}


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

import static java.util.Objects.requireNonNull;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.stream.Collectors;

import org.jooby.Env;
import org.jooby.Jooby;
import org.jooby.Session;

import com.github.benmanes.caffeine.cache.AsyncLoadingCache;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.CaffeineSpec;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.google.inject.Binder;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.google.inject.name.Names;
import com.google.inject.util.Types;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigValueFactory;

/**
 *
caffeine

 *

 * {@link Cache} services from Caffeine
 *

 *
 *
usage

 *
 *

 * App.java:
 *

 *

 * {
 *   use(CaffeineCache.newCache());
 *
 *   get("/", req {@literal ->} {
 *     Cache cache = req.require(Cache.class);
 *     // do with cache...
 *   });
 * }
 *

 *
 *
options

 *
 *
cache configuration

 *

 * A default cache will be created, if you need to control the number of entries, expire policy,
 * etc... set the caffeine.cache property in application.conf, like:
 *

 *
 *

 * caffeine.cache {
 *   maximumSize = 10
 * }
 *

 *
 * or via {@link CaffeineSpec} syntax:
 *
 *

 * caffeine.cache = "maximumSize=10"
 *

 *
 *
multiple caches

 *

 * Just add entries to: caffeine., like:
 *

 *
 *

 * # default cache (don't need a name on require calls)
 * caffeine.cache = "maximumSize=10"
 *
 * caffeine.cache1 = "maximumSize=1"
 *
 * caffeine.cacheX = "maximumSize=100"
 *

 *
 *

 * {
 *   get("/", req {@literal ->} {
 *     Cache defcache = req.require(Cache.class);
 *
 *     Cache cache1 = req.require("cache1", Cache.class);
 *
 *     Cache cacheX = req.require("cacheX", Cache.class);
 *   });
 * }
 *

 *
 *
type-safe caches

 *

 * Type safe caches are provided by calling and creating a new {@link CaffeineCache} subclass:
 *

 *
 *

 * {
 *   // please notes the {} at the line of the next line
 *   use(new CaffeineCache<Integer, String>() {});
 * }
 *

 *
 *

 * Later, you can inject this cache in a type-safe manner:
 *

 *
 *

 * @Inject
 * public MyService(Cache<Integer, String> cache) {
 *  ...
 * }
 *

 *
 *
session store

 *

 * This module comes with a {@link Session.Store} implementation. In order to use it you need to
 * define a cache named session in your application.conf file:
 *

 *
 *

 * caffeine.session = "maximumSize=10"
 *

 *
 * And set the {@link CaffeineSessionStore}:
 *
 *

 * {
 *   session(CaffeineSessionStore.class);
 * }
 *

 *
 * You can access to the ```session``` via name:
 *
 *

 * {
 *   get("/", req {@literal} {
 *     Cache cache = req.require("session", Cache.class);
 *   });
 * }
 *

 *
 * @author edgar
 * @author ben manes
 * @since 1.0.0.Final
 * @param <K> Cache key.
 * @param <V> Cache value.
 * @see CaffeineSessionStore
 */
public abstract class CaffeineCache<K, V> implements Jooby.Module {

  public interface Callback<K, V, C extends Cache<K, V>> {
    C apply(String name, Caffeine<K, V> builder);
  }

  public interface AsyncCallback<K, V> {
    AsyncLoadingCache<K, V> apply(String name, Caffeine<K, V> builder);
  }

  private static final String DEF = "caffeine";

  @SuppressWarnings("rawtypes")
  private BiFunction<String, Caffeine, Object> callback = (n, b) -> b.build();

  private final String name;

  /**
   * Creates a new {@link CaffeineCache} using the provided namespace.
   *
   * @param name Cache namespace.
   */
  public CaffeineCache(final String name) {
    this.name = name;
  }

  /**
   * Creates a new {@link CaffeineCache} using caffeine as cache namespace.
   */
  public CaffeineCache() {
    this(DEF);
  }

  /**
   * Creates a new {@link CaffeineCache} with {@link String} and {@link Object} types as key/value.
   *
   * @return A new {@link CaffeineCache}.
   */
  public static CaffeineCache<String, Object> newCache() {
    return new CaffeineCache<String, Object>() {
    };
  }

  /**
   * Configure a cache builder and creates a new {@link Cache}.
   *
   * @param configurer Configurer callback.
   * @return This instance.
   */
  public CaffeineCache<K, V> doWith(final Callback<K, V, Cache<K, V>> configurer) {
    requireNonNull(configurer, "Configurer callback is required.");
    this.callback = configurer::apply;
    return this;
  }

  /**
   * Configure a cache builder and creates a new {@link AsyncLoadingCache}.
   *
   * @param configurer Configurer callback.
   * @return This instance.
   */
  public CaffeineCache<K, V> doWithAsync(final AsyncCallback<K, V> configurer) {
    requireNonNull(configurer, "Configurer callback is required.");
    this.callback = configurer::apply;
    return this;
  }

  @SuppressWarnings({"unchecked", "rawtypes" })
  @Override
  public void configure(final Env env, final Config conf, final Binder binder) {
    Config gconf = conf.hasPath(name) ? conf : ConfigFactory.empty();

    gconf = gconf.withFallback(
        ConfigFactory.empty().withValue("caffeine.cache", ConfigValueFactory.fromAnyRef("")));

    gconf.getObject(name).unwrapped().forEach((name, spec) -> {
      Caffeine<K, V> cb = (Caffeine<K, V>) Caffeine.from(toSpec(spec));

      Object cache = callback.apply(name, cb);

      List<TypeLiteral> types = cacheType(name, cache, getClass().getGenericSuperclass());

      types.forEach(type -> {
        binder.bind(Key.get(type, Names.named(name)))
            .toInstance(cache);
        if (name.equals("cache")) {
          // unnamed cache for default cache
          binder.bind(type).toInstance(cache);
          // raw type for default cache
          binder.bind(type.getRawType()).toInstance(cache);
        }
        if (name.equals("session")) {
          binder.bind(Key.get(type, Names.named(name))).toInstance(cache);
          binder.bind(Key.get(type.getRawType(), Names.named(name))).toInstance(cache);
        }
      });
    });
  }

  @SuppressWarnings("rawtypes")
  private static List<TypeLiteral> cacheType(final String name, final Object cache,
      final Type superclass) {
    Class[] ctypes;
    if (cache instanceof AsyncLoadingCache) {
      ctypes = new Class[]{AsyncLoadingCache.class };
    } else if (cache instanceof LoadingCache) {
      ctypes = new Class[]{LoadingCache.class, Cache.class };
    } else {
      ctypes = new Class[]{Cache.class };
    }
    List<TypeLiteral> result = new ArrayList<>(ctypes.length);
    for (Class ctype : ctypes) {
      if (name.equals("session")) {
        result.add(TypeLiteral.get(Types.newParameterizedType(ctype, String.class, Session.class)));
      } else {
        result.add(TypeLiteral.get(Types.newParameterizedType(ctype, types(superclass))));
      }
    }
    return result;
  }

  @SuppressWarnings("unchecked")
  private String toSpec(final Object spec) {
    if (spec instanceof Map) {
      Map<String, Object> m = (Map<String, Object>) spec;
      return m.entrySet().stream()
          .map(e -> e.getKey() + "=" + e.getValue())
          .collect(Collectors.joining(","));
    }
    return spec.toString();
  }

  private static Type[] types(final Type superclass) {
    Type key = String.class;
    Type value = Object.class;
    if (superclass instanceof ParameterizedType) {
      ParameterizedType parameterized = (ParameterizedType) superclass;
      Type[] args = parameterized.getActualTypeArguments();
      key = args[0];
      value = args[1];
    }
    return new Type[]{key, value };
  }

}


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

import static java.nio.file.LinkOption.NOFOLLOW_LINKS;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import static java.nio.file.StandardWatchEventKinds.OVERFLOW;

import org.jooby.spi.WatchEventModifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.file.ClosedWatchServiceException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.function.BiConsumer;

class Watcher {

  private static final WatchEvent.Modifier HIGH = WatchEventModifier.modifier("HIGH");
  /** The logging system. */
  private final Logger log = LoggerFactory.getLogger(getClass());
  private final WatchService watcher;
  private volatile Map<WatchKey, Path> keys;
  private BiConsumer<Kind<?>, Path> listener;
  private ExecutorService executor;

  @SuppressWarnings("unchecked")
  static <T> WatchEvent<T> cast(final WatchEvent<?> event) {
    return (WatchEvent<T>) event;
  }

  public void start() {
    executor.execute(() -> {
      boolean process = true;
      try {
        while (process) {
          process = processEvents();
        }
      } catch (ClosedWatchServiceException ex) {
        log.trace("watch service closed", ex);
      }
    });
  }

  public void stop() throws IOException {
    watcher.close();
  }

  /**
   * Register the given directory with the WatchService
   */
  private void register(final Path dir) throws IOException {
    WatchKey key = dir.register(watcher, new Kind[]{ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY }, HIGH);
    keys.put(key, dir);
  }

  /**
   * Register the given directory, and all its sub-directories, with the
   * WatchService.
   */
  private void registerAll(final Path start) throws IOException {
    // register directory and sub-directories
    Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
      @Override
      public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs)
          throws IOException {
        register(dir);
        return FileVisitResult.CONTINUE;
      }
    });
  }

  public Watcher(final ExecutorService executor, final BiConsumer<Kind<?>, Path> listener, final Path... dirs)
      throws IOException {
    this.watcher = FileSystems.getDefault().newWatchService();
    this.keys = new HashMap<>();
    this.listener = listener;
    for (Path dir : dirs) {
      registerAll(dir);
    }

    this.executor = executor;
  }

  private boolean processEvents() {
    // wait for key to be signalled
    WatchKey key;
    try {
      key = watcher.take();
    } catch (InterruptedException x) {
      Thread.currentThread().interrupt();
      return false;
    }

    Path dir = keys.get(key);
    if (dir == null) {
      return true;
    }

    for (WatchEvent<?> event : key.pollEvents()) {
      Kind<?> kind = event.kind();

      // TBD - provide example of how OVERFLOW event is handled
      if (kind == OVERFLOW) {
        continue;
      }

      // Context for directory entry event is the file name of entry
      WatchEvent<Path> ev = cast(event);
      Path name = ev.context();
      Path child = dir.resolve(name);
      File file = child.toFile();

      if (file.isFile() || kind == ENTRY_DELETE) {
        listener.accept(kind, dir.resolve(name));
      }

      // if directory is created, and watching recursively, then
      // register it and its sub-directories
      if (kind == ENTRY_CREATE) {
        try {
          if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
            registerAll(child);
          }
        } catch (IOException x) {
          // ignore to keep sample readbale
        }
      }
    }

    // reset key and remove from set if directory no longer accessible
    boolean valid = key.reset();
    if (!valid) {
      keys.remove(key);

      // all directories are inaccessible
      return !keys.isEmpty();
    }
    return true;
  }

}


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

import static java.util.Objects.requireNonNull;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.jooby.Env;
import org.jooby.Jooby;
import org.jooby.Session;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheBuilderSpec;
import com.google.common.cache.LoadingCache;
import com.google.inject.Binder;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.google.inject.name.Names;
import com.google.inject.util.Types;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigValueFactory;

/**
 *
guava-cache

 *

 * {@link Cache} services from Guava
 *

 *
 *
usage

 *
 *

 * App.java:
 *

 *

 * {
 *   use(GuavaCache.newCache());
 *
 *   get("/", req {@literal ->} {
 *     Cache cache = req.require(Cache.class);
 *     // do with cache...
 *   });
 * }
 *

 *
 *
options

 *
 *
cache configuration

 *

 * A default cache will be created, if you need to control the number of entries, expire policy,
 * etc... set the guava.cache property in application.conf, like:
 *

 *
 *

 * guava.cache {
 *   maximumSize = 10
 *   concurrencyLevel = 2
 * }
 *

 *
 * or via {@link CacheBuilderSpec} syntax:
 *
 *

 * guava.cache = "maximumSize=10,concurrencyLevel=2"
 *

 *
 *
multiple caches

 *

 * Just add entries to: guava., like:
 *

 *
 *

 * # default cache (don't need a name on require calls)
 * guava.cache = "maximumSize=10"
 *
 * guava.cache1 = "maximumSize=1"
 *
 * guava.cacheX = "maximumSize=100"
 *

 *
 *

 * {
 *   get("/", req {@literal ->} {
 *     Cache defcache = req.require(Cache.class);
 *
 *     Cache cache1 = req.require("cache1", Cache.class);
 *
 *     Cache cacheX = req.require("cacheX", Cache.class);
 *   });
 * }
 *

 *
 *
type-safe caches

 *

 * Type safe caches are provided by calling and creating a new {@link GuavaCache} subclass:
 *

 *
 *

 * {
 *   // please notes the {} at the line of the next line
 *   use(new GuavaCache<Integer, String>() {});
 * }
 *

 *
 *

 * Later, you can inject this cache in a type-safe manner:
 *

 *
 *

 * @Inject
 * public MyService(Cache<Integer, String> cache) {
 *  ...
 * }
 *

 *
 *
session store

 *

 * This module comes with a {@link Session.Store} implementation. In order to use it you need to
 * define a cache named session in your application.conf file:
 *

 *
 *

 * guava.session = "maximumSize=10"
 *

 *
 * And set the {@link GuavaSessionStore}:
 *
 *

 * {
 *   session(GuavaSessionStore.class);
 * }
 *

 *
 * You can access to the ```session``` via name:
 *
 *

 * {
 *   get("/", req {@literal} {
 *     Cache cache = req.require("session", Cache.class);
 *   });
 * }
 *

 *
 * @author edgar
 * @since 0.15.0
 * @param <K> Cache key.
 * @param <V> Cache value.
 * @see GuavaSessionStore
 */
public abstract class GuavaCache<K, V> implements Jooby.Module {

  public interface Callback<K, V, C extends Cache<K, V>> {
    C apply(String name, CacheBuilder<K, V> builder);
  }

  private static final String DEF = "guava";

  private Callback<K, V, Cache<K, V>> callback = (n, b) -> b.build();

  private final String name;

  /**
   * Creates a new {@link GuavaCache} using the provided namespace.
   *
   * @param name Cache namespace.
   */
  public GuavaCache(final String name) {
    this.name = name;
  }

  /**
   * Creates a new {@link GuavaCache} using guava as cache namespace.
   */
  public GuavaCache() {
    this(DEF);
  }

  /**
   * Creates a new {@link GuavaCache} with {@link String} and {@link Object} types as key/value.
   *
   * @return A new {@link GuavaCache}.
   */
  public static final GuavaCache<String, Object> newCache() {
    return new GuavaCache<String, Object>() {
    };
  }

  /**
   * Configure a cache builder and creates a new {@link Cache}.
   *
   * @param configurer Configurer callback.
   * @return This instance.
   */
  public GuavaCache<K, V> doWith(final Callback<K, V, Cache<K, V>> configurer) {
    this.callback = requireNonNull(configurer, "Configurer callback is required.");
    return this;
  }

  @SuppressWarnings({"unchecked", "rawtypes" })
  @Override
  public void configure(final Env env, final Config conf, final Binder binder) {
    Config gconf = conf.hasPath(name) ? conf : ConfigFactory.empty();

    gconf = gconf.withFallback(
        ConfigFactory.empty().withValue("guava.cache", ConfigValueFactory.fromAnyRef("")));

    gconf.getObject(name).unwrapped().forEach((name, spec) -> {
      CacheBuilder<K, V> cb = (CacheBuilder<K, V>) CacheBuilder.from(toSpec(spec));

      Cache<K, V> cache = callback.apply(name, cb);

      List<TypeLiteral> types = cacheType(name, cache, getClass().getGenericSuperclass());

      types.forEach(type -> {
        binder.bind(Key.get(type, Names.named(name)))
            .toInstance(cache);
        if (name.equals("cache")) {
          // unnamed cache for default cache
          binder.bind(type).toInstance(cache);
          // raw type for default cache
          binder.bind(type.getRawType()).toInstance(cache);
        }
        if (name.equals("session")) {
          binder.bind(Key.get(type, Names.named(name))).toInstance(cache);
          binder.bind(Key.get(type.getRawType(), Names.named(name))).toInstance(cache);
        }
      });
    });
  }

  @SuppressWarnings("rawtypes")
  private static List<TypeLiteral> cacheType(final String name, final Cache cache,
      final Type superclass) {
    Class[] ctypes = cache instanceof LoadingCache ? new Class[]{LoadingCache.class, Cache.class }
        : new Class[]{Cache.class };
    List<TypeLiteral> result = new ArrayList<>(ctypes.length);
    for (Class ctype : ctypes) {
      if (name.equals("session")) {
        result.add(TypeLiteral.get(Types.newParameterizedType(ctype, String.class, Session.class)));
      } else {
        result.add(TypeLiteral.get(Types.newParameterizedType(ctype, types(superclass))));
      }
    }
    return result;
  }

  @SuppressWarnings("unchecked")
  private String toSpec(final Object spec) {
    if (spec instanceof Map) {
      Map<String, Object> m = (Map<String, Object>) spec;
      return m.entrySet().stream()
          .map(e -> e.getKey() + "=" + e.getValue())
          .collect(Collectors.joining(","));
    }
    return spec.toString();
  }

  private static Type[] types(final Type superclass) {
    Type key = String.class;
    Type value = Object.class;
    if (superclass instanceof ParameterizedType) {
      ParameterizedType parameterized = (ParameterizedType) superclass;
      Type[] args = parameterized.getActualTypeArguments();
      key = args[0];
      value = args[1];
    }
    return new Type[]{key, value };
  }

}