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

/**
 * <h1>Asset compiler</h1>
 * <p>
 * Process static files by validate or modify them in some way.
 * </p>
 *
 * @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:
   *
   * <pre>
   * assets {
   *   fileset {
   *     home: [home.css, home.js]
   *   }
   * }
   * </pre>
   *
   * This method returns <code>home.css</code> and <code>home.js</code> for <code>home</code> 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:
   *
   * <pre>
   * {
   *   assets {
   *     fileset {
   *       lib: [js/lib/jquery.js],
   *       home: [css/style.css, js/home.js]
   *     }
   *   }
   * }
   * </pre>
   *
   * This method returns a set with <code>/css/**</code> and <code>/js/**</code> 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:
   *
   * <pre>
   * {
   *   assets {
   *     fileset {
   *       mypage: [mypage.js, mypage.css]
   *     }
   *   }
   * }
   * </pre>
   *
   * <p>
   * This method returns <code>mypage.js</code> for <code>mypage</code> fileset.
   * </p>
   *
   * @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:
   *
   * <pre>
   * {
   *   assets {
   *     fileset {
   *       mypage: [mypage.js, mypage.css]
   *     }
   *   }
   * }
   * </pre>
   *
   * <p>
   * This method returns <code>mypage.js</code> for <code>mypage</code> fileset.
   * </p>
   *
   * @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);
  }

}
