package mosaiccreator;

import javax.swing.JFileChooser;
import java.io.File;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.awt.Frame;

/**
 *
 * <p>Title: Mosaic Saver </p>
 * <p>Description: saves the mosaic as a .mosaic file</p>
 * @author Lance Finfrock
 * @version 1.0
 */
public class MosaicSaver
    implements Runnable {

  private Frame windowCameFrom;

  /**
   *
   * @param w Frame the window that called the class
   */
  public MosaicSaver(Frame w) {
    this.windowCameFrom = w;

    //start the local thread
    Thread local = new Thread(this);
    local.setPriority(Thread.MIN_PRIORITY);
    local.start();

  }

  public void run() {
    this.saveMosaic();
  }

  /**
   * saves the mosaic to a file chosen from a file browser
   */
  public void saveMosaic() {
    //create the file chooser
    JFileChooser fc = new JFileChooser();
    String pathName = "";

    //this allows only the .mosaic file to be seen and folders
    fc.addChoosableFileFilter(new MosaicFilter());
    fc.setAcceptAllFileFilterUsed(false);

    //this puts my icon to be seen for .mosaic
    fc.setFileView(new MosaicFileView());

    //this Shows the chooser
    int returnVal = fc.showDialog(this.windowCameFrom, "Save");

    //if they choose a correct file
    if (returnVal == JFileChooser.APPROVE_OPTION) {
      File file = fc.getSelectedFile();

      //check if the user typed .mosaic
      if (file.getName().endsWith(".mosaic")) {
        pathName = file.getPath();
      }
      else {
        pathName = file.getPath() + ".mosaic";
      }

      try {
        PrintWriter outData = new PrintWriter(new BufferedWriter(new FileWriter(
            pathName)), true);

        //write all the information for the mosaic

        //write the original mosaic image
        outData.println(MainWindow.currentMosaic.DivionsWide);
        outData.println(MainWindow.currentMosaic.DivionsHigh);
        outData.println(MainWindow.currentMosaic.OriginalPicture);

        //write all the mosaic pieces
        for (int i = 0; i < MainWindow.currentMosaic.subPiecesPixels.length; i++) {
          outData.println(MainWindow.currentMosaic.subPiecesPixels[i]);
        }

      }
      catch (IOException ex) {
        System.err.println("error writing Mosaic");
      }
    }
  }

}
