package futils;

import java.awt.*;
import java.io.*;
import javax.swing.*;

public final class WriterUtil {
  /**
   * Don't let anyone instantiate this class.
   */
  private WriterUtil() {
  }


  // Some versions of windows will
// create a .* suffix on a file name
// The following code will strip it:
  public static String FilterFileNameBug(String fname) {
    if (fname.endsWith(".*.*")) {
      fname = fname.substring(0, fname.length() - 4);
    }
    return fname;
  }

  public static String getWriteDirectoryName(String prompt) {
    FileDialog dialog = new FileDialog(
        new Frame(),
        prompt,
        FileDialog.SAVE);
    dialog.show();
    String fs = dialog.getDirectory();
    dialog.dispose();
    return FilterFileNameBug(fs);
  }


  public static File getDirFileAWT(String prompt) {
    FileDialog fd =
        new FileDialog(
            new Frame(),
            prompt);
    fd.show();
    String dirName = fd.getDirectory();
    fd.dispose();
    return new File(dirName);
  }

  public static File JGetDirFile(String prompt) {
    JFileChooser jfc = new JFileChooser();
    jfc.showOpenDialog(new JFrame());
    File f =  jfc.getSelectedFile();
    return f.getParentFile();
  }
  public static File getDirFile(String prompt) {
    if (Futil.isSwing()) return JGetDirFile(prompt);
    return getDirFileAWT(prompt);
  }



  public static void writeFilteredHrefFile(
      String inputName,
      String outputName) {
    System.out.println(
        "Filtering:\t" +
        inputName +
        "\t>\t" +
        outputName);
    try {
      FileReader is = new FileReader(inputName);
      StreamTokenizer st =
          new StreamTokenizer(is);

      FileOutputStream fos = new FileOutputStream(outputName);
      PrintWriter output = new PrintWriter(fos);
      int i;
      int next = 0;
      st.resetSyntax();
      st.wordChars(0, 255);
      st.quoteChar('"');
      while ((next = st.nextToken()) != st.TT_EOF) {
        switch (next) {
          case '"':
            output.print('"');
            for (i = 0; i < st.sval.length(); i++)
              if (st.sval.charAt(i) == ' ')
                output.print("%20");
              else
                output.print(st.sval.charAt(i));
            output.print('"');
            break;
          case StreamTokenizer.TT_WORD:
            output.print(st.sval + " ");
            break;
          case StreamTokenizer.TT_NUMBER:
            output.print(st.nval + " ");
            break;
          case StreamTokenizer.TT_EOL:
            output.println();
            break;
        } // end switch
      } // end while
      is.close();
      fos.close();
    } // end try
    catch (Exception exe) {
      System.out.println("writeFilteredHrefFile:er!");
    }
  }

  public static void main(String[] args) {
    FileDialog dialog = new FileDialog(
        new Frame(),
        null,
        FileDialog.SAVE);
    dialog.show();
    String fs = dialog.getDirectory() + dialog.getFile();
    dialog.dispose();
    System.out.println(FilterFileNameBug(fs));

  }


  public void lowerFileNames(File thePath) {
    String[] fileNames = thePath.list();
    String pathstr = thePath.getPath();
    for (int i = 0;
         fileNames != null &&
        i < fileNames.length; i++) {
      String aFileName = fileNames[i];
      String newFileName = aFileName.toLowerCase();
      File theFile = new File(pathstr, aFileName);
      if (theFile.isFile()) {
        //rename theFile to lower case
        System.out.print(i + ":" + aFileName);
        theFile.renameTo(new File(pathstr, newFileName));
        System.out.println("\t==>\t" + newFileName);
      } else {
        //case theFile is Dir, in the Dir, repeat same procedure
        System.out.println("Dir:" + aFileName);
        lowerFileNames(new File(pathstr + aFileName));
      }
    }
    return;
  }//lowerFileNames

  /** Convert a file to a FileWriter
   *
   * @param f The input File
   * @return A FileWriter obtained from the file
   */
  public static FileWriter getFileWriter(File f) {
    try {
      return new FileWriter(f);
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }
  }

  /** write a string out to a file
   *
   * @param s The string to write out.
   */
  public static void writeString(String s) {
    FileWriter fw = getFileWriter(
        "enter output file");
    try {
      fw.write(s);
      fw.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  /** prompt the user for a file and return a writer.
   *
   * @param prompt the string prompt displayed to the user.
   * @return A FileWriter obtained from a use selection
   */
  public static FileWriter getFileWriter(
      String prompt) {
    return getFileWriter(Futil.getWriteFileSwing(prompt));
  }

  /** "@param prompt
   */
  public static BufferedWriter
      getBufferedWriter(String prompt) {
    File f = Futil.getWriteFileSwing(prompt);
    return getBufferedWriter(f);
  }

  /** "@param f
   */
  public static BufferedWriter
      getBufferedWriter(File f) {
    BufferedWriter bw = null;
    try {
      bw = new BufferedWriter(
          new FileWriter(f));
    } catch (IOException e) {
    }
    return bw;
  }

  /** "@param bw
   */
  public static void close(BufferedWriter bw) {
    try {
      bw.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static String getWriteDirectoryName() {
    FileDialog dialog = new FileDialog(
        new Frame(),
        "Enter file name",
        FileDialog.SAVE);
    dialog.show();
    String fs = dialog.getDirectory();
    System.out.println("Opening file: " + fs);
    dialog.dispose();
    return Futil.FilterFileNameBug(fs);
  }

  public static void close(FileWriter fw) {
    try {
      fw.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static File[] getFiles(String prompt) {
    return
        Futil.getReadFile(
            prompt).listFiles(
                new FileFilter());
  }

  /** "@param bw
   *
   * @param bw
   * @param o
   */
  public static void println(
      BufferedWriter bw, Object o) {
    try {
      bw.write(o + "\n");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

    public static String getSaveFileName(String prompt) {
        FileDialog fd = new
                FileDialog(new Frame(), prompt, FileDialog.SAVE);
        fd.setVisible(true);
        fd.setVisible(false);
        String fn = fd.getDirectory() + fd.getFile();
        if (fd.getFile() == null) return null; //usr canceled
        return fn;
    }

    public static String getSaveName(String prompt) {
        FileDialog fd = new
                FileDialog(new Frame(), prompt, FileDialog.SAVE);
        fd.setVisible(true);
        fd.setVisible(false);
        String fn = fd.getFile();
        if (fd.getFile() == null) return null; //usr canceled
        return fn;
    }

    public static String getSaveDirectoryName(String prompt) {
        FileDialog fd = new
                FileDialog(new Frame(), prompt, FileDialog.SAVE);
        fd.setVisible(true);
        fd.setVisible(false);
        return fd.getDirectory();
    }


}