package ro.isdc.wro.model.resource.processor.support;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import ro.isdc.wro.util.WroUtil;


/**
 * Encapsulates the matcher creation for css import statements detection. Useful to isolate unit tests. TODO prefer a
 * fluent interface implementation for this class.
 *
 * @author Alex Objelean
 * @created 19 Feb 2013
 * @since 1.6.3
 */
public class CssImportInspector {
  private static final Pattern PATTERN = Pattern.compile(WroUtil.loadRegexpWithKey("cssImport"));
  private static final String REGEX_IMPORT_FROM_COMMENTS = WroUtil.loadRegexpWithKey("cssImportFromComments");
  /**
   * The index of the url group in regex.
   */
  private static final int INDEX_URL = 1;
  private final Matcher matcher;

  public CssImportInspector(final String cssContent) {
    matcher = getMatcher(removeImportsFromComments(cssContent));
  }

  protected Matcher getMatcher(final String cssContent) {
    return PATTERN.matcher(cssContent);
  }

  /**
   * Removes all @import statements from css.
   */
  public String removeImportStatements() {
    final StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
      // replace @import with empty string
      matcher.appendReplacement(sb, "");
    }
    matcher.appendTail(sb);
    return sb.toString();
  }

  /**
   * @return true if checked css content contains an @import statement.
   */
  public boolean containsImport() {
    return matcher.find();
  }

  /**
   * @return a list of all resources imported using @import statement.
   */
  public List<String> findImports() {
    final List<String> list = new ArrayList<String>();
    while (matcher.find()) {
      list.add(extractImportUrl(matcher));
    }
    return list;
  }

  /**
   * Override this method to provide a custom way of extracting the imported resource url.
   *
   * @param matcher
   *          the {@link Matcher} inspecting the parsed css content.
   * @return the url of the imported resources.
   */
  protected String extractImportUrl(final Matcher matcher) {
    return matcher.group(INDEX_URL);
  }

  /**
   * Removes all import statements from provided css content.
   *
   * @return the css content with import statement removed.
   * @VisibleForTesting
   */
  String removeImportsFromComments(final String content) {
    return content.replaceAll(REGEX_IMPORT_FROM_COMMENTS, "");
  }
}

@@ -942,16 +942,158 @@
 );%0A  %7D%0A%0A
+  /**%0A   * @return a %7B@link Matcher%7D for the processed content using the regexp responsible for identifying css import%0A   * statements.%0A   */%0A
   protec
@@ -1134,32 +1134,32 @@
 g cssContent) %7B%0A
-
     return PATTE
@@ -1254,16 +1254,22 @@
  public 
+final 
 String r
@@ -1613,16 +1613,22 @@
  public 
+final 
 boolean 
@@ -1770,16 +1770,22 @@
  public 
+final 
 List%3CStr
@@ -2471,18 +2471,24 @@
 g%0A   */%0A
-
   
+final 
 String r

add javadocs