/*
 * SonarQube JavaScript Plugin
 * Copyright (C) 2011-2016 SonarSource SA
 * mailto:contact AT sonarsource DOT com
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package org.sonar.plugins.javascript.minify;

import java.io.File;
import java.nio.charset.Charset;

/**
 * An object to assess if a .js file is a minified file or not.
 * <p>
 * An instance of this class is likely to consider as minified a .js file that,
 * although formally not minified, has an unusually high average line length.
 * This situation is typical of files that have been generated by some tool.
 * Such files are of poor interest as regards a SonarQube analysis.
 */
public class MinificationAssessor {

  private static final int DEFAULT_AVERAGE_LINE_LENGTH_THRESHOLD = 200;

  private Charset encoding;

  /**
   * Value of the average line length 
   * (= number of chars in the file / number of lines in the file)
   * below which a file is not assessed as being a minified file.   
   */
  private int averageLineLengthThreshold;

  public MinificationAssessor(Charset encoding) {
    this(encoding, DEFAULT_AVERAGE_LINE_LENGTH_THRESHOLD);
  }

  public MinificationAssessor(Charset encoding, int averageLineLengthThreshold) {
    this.encoding = encoding;
    this.averageLineLengthThreshold = averageLineLengthThreshold;
  }

  public boolean isMinified(File file) {
    return isJavaScriptFile(file) &&
      (hasMinifiedFileName(file) || hasExcessiveAverageLineLength(file));
  }

  private static boolean hasMinifiedFileName(File file) {
    String fileName = file.getName();
    return fileName.endsWith("-min.js") || fileName.endsWith(".min.js");
  }

  private static boolean isJavaScriptFile(File file) {
    return file.getName().endsWith(".js");
  }

  private boolean hasExcessiveAverageLineLength(File file) {
    int averageLineLength = new AverageLineLengthCalculator(file, encoding).getAverageLineLength();
    return averageLineLength > averageLineLengthThreshold;
  }

}
