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

import com.google.common.collect.ImmutableList;
import com.google.inject.Binder;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import org.jooby.Env;
import org.jooby.Jooby;
import org.jooby.Route;
import org.jooby.Router;
import org.jooby.handlers.AssetHandler;
import org.jooby.internal.assets.AssetVars;
import org.jooby.internal.assets.FileSystemAssetHandler;
import org.jooby.internal.assets.LiveCompiler;
import org.jooby.internal.assets.LiveProgressBar;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;

/**
 * <h1>assets</h1>
 * <p>
 * The asset module is library to concatenate, minify or compress JavaScript and CSS
 * assets. It also adds the ability to write these assets in other languages and process/compile
 * them to another language. Finally, it help you to write high quality code by validate JavaScript
 * and CSS too.
 * </p>
 * <p>
 * A variety of processors are available (jshint, csslint, jscs, uglify, closure-compiler, etc..),
 * but
 * also you might want to write your owns.
 * </p>
 *
 * <h2>getting started</h2>
 * <p>
 * The first thing you need to do is to define your assets. Definition is done in your
 * <code>.conf</code> file or in a special file: <code>assets.conf</code>.
 * </p>
 *
 * <strong>assets.conf</strong>
 * <pre>
 * assets {
 *   fileset {
 *     home: [assets/home.js, assets/home.css]
 *   }
 * }
 * </pre>
 *
 * <strong>App.java</strong>
 * <pre>
 *  {
 *    use(new Assets());
 *  }
 * </pre>
 *
 * <p>
 * The assets module will publish 4 request local variables for <code>home</code> fileset:
 * <code>_css</code> and <code>_js</code> each of these variables is a list of string with the
 * corresponding files. There are two more variables: <code>_styles</code> and <code>_scripts</code>
 * :
 * </p>
 *
 * <pre>
 *   &lt;html&gt;
 *   &lt;head&gt;
 *     {{{home_styles}}}
 *   &lt;body&gt;
 *     ...
 *     {{{home_scripts}}
 *   &lt;/body&gt;
 *   &lt;/head&gt;
 *   &lt;/html&gt;
 * </pre>
 *
 * <p>
 * The variables: <code>_styles</code> and <code>_scripts</code> produces one ore more
 * <code>link</code> and <code>script</code> tags. The example above, shows you how to
 * render these variables in the template engine of your choice (handlebars, here).
 * </p>
 *
 * <p>
 * Now, let's see how to configure the Maven plugin to process our assets at build-time:
 * </p>
 *
 * <strong>pom.xml</strong>
 *
 * <pre>
 *   &lt;plugin&gt;
 *     &lt;groupId&gt;org.jooby&lt;/groupId&gt;
 *     &lt;artifactId&gt;jooby-maven-plugin&lt;/artifactId&gt;
 *     &lt;executions&gt;
 *       &lt;execution&gt;
 *         &lt;goals&gt;
 *           &lt;goal&gt;assets&lt;/goal&gt;
 *         &lt;/goals&gt;
 *       &lt;/execution&gt;
 *     &lt;/executions&gt;
 *   &lt;/plugin&gt;
 * </pre>
 *
 * <p>
 * The plugin will process all your assets and include them to the final <code>.jar</code>,
 * <code>.zip</code> or <code>.war</code>.
 * </p>
 *
 * <p>
 * Cool, isn't?
 * </p>
 *
 * <h2>how it works?</h2>
 * <p>
 * The <code>assets.fileset</code> defines all your assets. In <code>dev</code> assets are
 * rendered/processed at runtime. In <code>prod</code> at built-time.
 * </p>
 * <p>
 * Assets are rendered at runtime using <code>*_styles</code> or <code>*_scripts
 * </code> variables. So you define your assets in one single place: <code>assets.conf</code>.
 * </p>
 * <p>
 * Also, at build-time, the asset compiler concatenates all the files from a fileset and
 * generate a fingerprint. The fingerprint is a SHA-1 hash of the content of the fileset. Thanks to
 * the fingerprint an asset can be cached it for ever! Defaults cache max age is:
 * <code>365 days</code>.
 * </p>
 * <p>
 * That isn't all! the <code>*_styles</code> and <code>*_scripts</code> are updated with the
 * fingerprint version of assets, so you don't have to do or change anything in your views! It just
 * works!!!
 * </p>
 *
 * <h2>fileset</h2>
 * <p>
 * A fileset is a group of assets within a name. The fileset name is expanded into 4 request local
 * variables, for example:
 * </p>
 * <pre>
 * assets {
 *   fileset {
 *     home: [assets/home.js, assets/home.css]
 *     pageA: [assets/pageA.js, assets/pageA.css]
 *   }
 * }
 * </pre>
 *
 * <p>
 * Produces 4 variables for <code>home</code>:
 * </p>
 *
 * <ul>
 * <li>home_css: a list of all the <code>css</code> files</li>
 * <li>home_styles: a string, with all the <code>css</code> files rendered as <code>link</code> tags
 * </li>
 * <li>home_js: a list of all the <code>js</code> files</li>
 * <li>home_scripts: a string, with all the <code>js</code> files rendered as <code>script</code>
 * tags</li>
 * </ul>
 *
 * <p>
 * Another 4 variables will be available for the <code>pageA</code> fileset!
 * </p>
 *
 * <h3>extending filesets</h3>
 * <p>
 * Extension or re-use of filesets is possible via the: <code>&lt;</code> operator:
 * </p>
 * <pre>
 * assets {
 *   fileset {
 *     base: [js/lib/jquery.js, css/normalize.css]
 *     home &lt; base: [js/home.js]
 *     pageA &lt; base: [js/pageA.js]
 *   }
 * }
 * </pre>
 *
 * <h2>processors</h2>
 * <p>
 * An {@link AssetProcessor} usually checks or modify an asset content in one way or another. They
 * are defined in the <code>assets.conf</code> files using the <code>pipeline</code> construction:
 * </p>
 *
 * <pre>
 * assets {
 *   fileset {
 *     home: [js/home.js, css/home.css]
 *   }
 *
 *   pipeline {
 *     dev: [jshint, jscs, csslint, sass]
 *     dist: [uglify, sass, clean-css]
 *   }
 * }
 * </pre>
 *
 * <p>
 * Example above, defines a <strong>pipeline</strong> for development (dev) and one generic for prod
 * (dist).
 * </p>
 * <p>
 * In <code>dev</code> the code will be checked it against js-hint, jscs and csslint! But
 * also, we want to use sass for css!!
 * </p>
 * <p>
 * The generic <code>dist</code> will be used it for any other environment and here we just want to
 * optimize our javascript code with uglify, compile sass to css and then optimize the css using
 * clean-css!!
 * </p>
 *
 * <p>
 * For more information about processor, have a look at the {@link AssetProcessor} doc.
 * </p>
 *
 * <h2>aggregators</h2>
 * <p>
 * Contributes new or dynamically generated content to a <code>fileset</code>. Content generated by
 * an aggregator might be processed by an {@link AssetProcessor}.
 * </p>
 *
 * <h3>how to use it?</h3>
 * <p>
 * First thing to do is to add the dependency:
 * </p>
 * <pre>
 *   &lt;dependency&gt;
 *     &lt;groupId&gt;org.jooby&lt;/groupId&gt;
 *     &lt;artifactId&gt;jooby-assets-dr-svg-sprites&lt;/artifactId&gt;
 *     &lt;scope&gt;provided&lt;/scope&gt;
 *   &lt;/dependency&gt;
 * </pre>
 *
 * <p>
 * Did you see the <strong>provided</strong> scope? We just need the aggregator for development,
 * because assets are processed at runtime. For <code>prod</code>, assets are processed at
 * built-time via Maven/Gradle plugin, so we don't need it. This also, helps to keep our
 * dependencies and the jar size small.
 * </p>
 *
 * <p>
 * Now we have the dependency all we have to do is to add the <code>svg-sprites</code> aggregator to
 * a fileset:
 * </p>
 *
 * <pre>
 * assets {
 *   fileset {
 *     home: [
 *       // 1) Add the aggregator to a fileset
 *       svg-sprites,
 *       css/style.css,
 *       js/app.js
 *     ]
 *   }
 *
 *   svg-sprites {
 *     // 2) The `css/sprite.css` file is part of the `home` fileset.
 *     spritePath: "css/sprite.css"
 *
 *     spriteElementPath: "images/svg",
 *   }
 * }
 * </pre>
 *
 * <p>
 * Here for example, the <code>svg-sprites</code> aggregator contributes the
 * <code>css/sprite.css</code> file to the <code>home</code> fileset. The fileset then looks like:
 * </p>
 *
 * <pre>
 * assets {
 *   fileset {
 *     home: [
 *       css/sprite.css,
 *       css/style.css,
 *       js/app.js
 *     ]
 *   }
 * }
 * </pre>
 * <p>
 * Replaces the aggregator name with one or more files from {@link AssetAggregator#fileset()}
 * method.
 * </p>
 *
 * @author edgar
 * @since 0.11.0
 */
public class Assets implements Jooby.Module {

  @Override
  public void configure(final Env env, final Config config, final Binder binder) throws Throwable {
    String envname = env.name();
    boolean dev = "dev".equals(envname);
    ClassLoader loader = getClass().getClassLoader();
    Config conf = conf(dev, loader, config);
    String cpath = config.getString("application.path");
    ClassLoader assetClassLoader = AssetClassLoader.classLoader(loader);
    AssetCompiler compiler = new AssetCompiler(assetClassLoader, conf);

    Router routes = env.router();
    List<String> dist = dev ? ImmutableList.of("dev") : ImmutableList.of(envname, "dist");
    String prefix = dist.stream()
        .filter(it -> conf.hasPath("assets." + it + ".prefix"))
        .findFirst()
        .map(it -> conf.getString("assets." + it + ".prefix"))
        .orElse(cpath);
    routes.use("*", "*", new AssetVars(compiler, prefix, !dev)).name("/assets/vars");
    boolean watch = conf.hasPath("assets.watch") ? conf.getBoolean("assets.watch") : dev;
    // live compiler?
    AssetHandler handler;
    if (watch) {
      Path publicDir = Paths.get(conf.getString("user.dir"), "public");
      Path workdir = Paths.get(conf.getString("assets.outputDir"));
      handler = new FileSystemAssetHandler("/", workdir, publicDir);
      LiveCompiler liveCompiler = new LiveCompiler(compiler, workdir);

      routes.use("*", "*", liveCompiler)
          .name("/assets/compiler");
      // is there a jooby:run restart?
      int counter = Integer.parseInt(System.getProperty("joobyRun.counter", "0"));
      if (counter == 0) {
        // nop, force full compilation:
        long start = System.currentTimeMillis();
        LiveProgressBar progressBar = new LiveProgressBar();
        compiler.setProgressBar(progressBar);
        Future<Map<String, List<File>>> future = liveCompiler.sync();
        env.onStarted(() -> {
          Logger log = LoggerFactory.getLogger(AssetCompiler.class);
          if (!future.isDone()) {
            progressBar.start();
          }
          Map<String, List<File>> result = future.get();
          long end = System.currentTimeMillis();
          log.info("{}", compiler
              .summary(result, workdir, "dev", end - start));
          /** Watch for changes: */
          liveCompiler.watch();
        });
      } else {
        // yes, then watch for changes on started:
        env.onStarted(liveCompiler::watch);
      }
      env.onStop(liveCompiler::stop);
    } else {
      handler = new AssetHandler("/");
    }

    handler.etag(conf.getBoolean("assets.etag"))
        .cdn(conf.getString("assets.cdn"))
        .lastModified(conf.getBoolean("assets.lastModified"));

    handler.maxAge(conf.getString("assets.cache.maxAge"));

    // release engine (if any)
    env.onStop(compiler::stop);

    compiler.patterns().forEach(pattern -> routes.get(pattern, handler));
  }

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

  private Config conf(final boolean dev, final ClassLoader loader, final Config conf) throws
      IOException {
    if (!dev) {
      Config[] confs = {
          ConfigFactory.parseResources(loader,
              "assets." + conf.getString("application.env").toLowerCase() + ".conf"),
          ConfigFactory.parseResources(loader, "assets.dist.conf"),
          ConfigFactory.parseResources(loader, "assets.conf")};
      for (Config it : confs) {
        if (!it.isEmpty()) {
          return it.withFallback(conf).resolve();
        }
      }
    }
    if (loader.getResource("assets.conf") == null) {
      throw new FileNotFoundException("assets.conf");
    }
    return ConfigFactory.parseResources(loader, "assets.conf").withFallback(conf).resolve();
  }

}
