/**
 * Class FileSaver
 * Shows a dialog for saving a file and eventually saves it
 */
package rmi.rmiSynth.lex;

import javax.swing.*;
import java.awt.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class FileSaver {
  /**
   * Method createFile
   * Promts user for a filename and saves the file
   * @param source Future file content
   * @param fileName Name of the file
   * @return void
   */
  public void createFile(String source, String fileName) {
    String fn = getSaveFileName("save file as", fileName);  //Show dialog
    //If no name is specified show warning and get out
    if (fn == null) {
      JOptionPane.showMessageDialog
          (null, "No filename is specified! operation aborted.", "Wait a second",
           JOptionPane.INFORMATION_MESSAGE);
      return;
    }
    //Create new file <fn>
    File f = new File(fn);
    BufferedWriter bw = null;
    // Open file
    try {
      bw = new BufferedWriter(new FileWriter(f));
    } catch (Exception e) {
    }
    //Write
    try {
      bw.write(source);
    } catch (Exception e) {
    }
    //Close
    try {
      bw.close();
    } catch (Exception e) {
    }
  }

  /**
   * Method getSaveFileName
   * Shows Save File dialog
   * @param prompt Prompt to show in title bar
   * @param fileName Name of the file
   * @return fn File name that user typed in
   */
  public String getSaveFileName(String prompt, String fileName) {
    //Prepare dialog
    FileDialog fd = new FileDialog(new Frame(), prompt, FileDialog.SAVE);
    fd.setFile(fileName + ".java");
    //Show it
    fd.setVisible(true);
    fd.setVisible(false);
    //Get file name
    String fn = fd.getDirectory() + fd.getFile();
    if (fd.getFile() == null) return null;
    return fn;
  }
}