/*
 * Copyright (c) 2009, Takeyuki Nagao
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or
 * without modification, are permitted provided that the
 * following conditions are met:
 * 
 *  * Redistributions of source code must retain the above
 *    copyright notice, this list of conditions and the
 *    following disclaimer.
 *  * Redistributions in binary form must reproduce the above
 *    copyright notice, this list of conditions and the
 *    following disclaimer in the documentation and/or other
 *    materials provided with the distribution.
 *    
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 */

package dvi.v2.cli.tools;
import java.io.File;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;

import dvi.DviException;
import dvi.DviFontSpec;
import dvi.api.DviContext;
import dvi.api.DviDocument;
import dvi.ctx.DefaultDviContext;
import dvi.util.Benchmark;
import dvi.util.DviUtils;
import dvi.util.csv.StringCsvData;
public class ScanFonts {
  private static final Logger LOGGER = Logger.getLogger(ScanFonts.class.getName());
  
  public static void printUsage(PrintStream out)
  {
    out.println(ScanFonts.class.getName() + " - List fonts in the specified documents.");
    out.println("Command line arguments: <input-files>");
    out.println("Output will be written on fontspecs.csv");
  }
  
  public static void main(String[] args)
  throws Exception
  {
    if (args.length == 0) {
      printUsage(System.out);
      System.out.println("error: No inputs");
    } else {
      final DviContext ctx = new DefaultDviContext();
      Benchmark bm = new Benchmark();
      bm.begin("Scanning the fonts");
      Set<DviFontSpec> fonts = new HashSet<DviFontSpec>();
      for (String filename : args) {
        File file = new File(filename);
        if (filename.endsWith(".list")) {
          String [] lines = DviUtils.removeComments
            (DviUtils.readLinesFromFile(file), "#");
          for (String line : lines) {
            if (line == null) continue;
            if (line.trim().equals(""))
              continue;
            File file2 = new File(line);
            addFonts(ctx, fonts, file2);
            bm.addSample();
          }
        } else {
          addFonts(ctx, fonts, file);
          bm.addSample();
        }
      }
      bm.end();
      System.err.println(bm.format());
      final StringCsvData csv = new StringCsvData();
      for (DviFontSpec fs : fonts) {
        csv.beginLine();
        csv.put("cs", String.valueOf(fs.checkSum()));
        csv.put("ss", String.valueOf(fs.spaceSize()));
        csv.put("ds", String.valueOf(fs.designSize()));
        csv.put("al", String.valueOf(fs.fontName().areaLength()));
        csv.put("nl", String.valueOf(fs.fontName().nameLength()));
        csv.put("name", fs.fontName().name());
        csv.endLine();
      }
      LOGGER.info("Number of font specs found: " + fonts.size());
      
      File outputCsvFile = new File("fontspecs.csv");
      csv.writeToFile(outputCsvFile);
      LOGGER.info("Output written on " + outputCsvFile);
    }
  }
  
  private static void addFonts(DviContext ctx, Set<DviFontSpec> fonts, File file) throws MalformedURLException, DviException {
    try {
      if (file == null) return;
      LOGGER.info("Scanning file: " + file);
      DviDocument doc = ctx.openDviDocument(file.toURL());
      fonts.addAll(doc.getFontTable().values());
    } catch (DviException e) {
      LOGGER.severe("Failed to read DVI file: " + file);
    }
  }
}
