package mosaiccreator;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
import javax.swing.JFileChooser;

/**
 * <p>Title: Mosaic JPEG Saver </p>
 * <p>Description: Save the mosaic to the size pass in as a jpeg </p>
 * @author Lance Finfrock
 * @version 1.0
 */
public class MosaicJPEGSaver implements Runnable{

  private Frame windowCamefrom;
  private double BackgroundIntensity;
  private int Width;
  private int Height;

  /**
   * @param window Frame the window that created this class
   * @param backgroundInt double the blending level
   * @param width int the width the mosaic is save as
   * @param height int the height the mosaic is save as
   */
  public MosaicJPEGSaver( Frame window,
                     double backgroundInt,
                     int width,
                     int height) {

    this.windowCamefrom = window;
    this.BackgroundIntensity = backgroundInt;
    this.Width = width;
    this.Height = height;
    Thread local = new Thread(this);
    local.setPriority(Thread.MIN_PRIORITY);
    local.start();
  }

  public void run() {
    BufferedImage image = MainWindow.currentMosaic.createMosaicPicture(this.Width, this.Height,this.BackgroundIntensity, this.windowCamefrom);

    this.saveBufferedImage(image);
  }

  /**
   * allows the user to choose the directory where to be saved and save the image as a jpeg
   * @param image BufferedImage the image to be saved
   */
  public void saveBufferedImage(BufferedImage image) {
    JFileChooser fc = new JFileChooser();
    String pathName = "";

    //only allowing the chooser to see images
    fc.addChoosableFileFilter(new ImageFilter());
    fc.setAcceptAllFileFilterUsed(false);

    //Showing the chooser
    int returnVal = fc.showDialog(windowCamefrom, "Save");

    //if the user choose the correct file
    if (returnVal == JFileChooser.APPROVE_OPTION) {
      File file = fc.getSelectedFile();
      if (file.getName().endsWith(".jpeg") || file.getName().endsWith(".jpg") ||
          file.getName().endsWith(".JPG") || file.getName().endsWith(".JPEG")) {
        pathName = file.getPath();
      }
      else {
        pathName = file.getPath() + ".jpg";
      }
      try {
        ImageIO.write(image, "jpg", new File(pathName));
      }
      catch (Exception e) {}
    }
  }
}
