package GUI;

import java.awt.*;
import java.awt.event.*;
import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.ImageIcon;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.io.*;
import java.util.*;
import javax.imageio.*;
import javax.imageio.stream.*;

import com.sun.jimi.core.Jimi;
import com.sun.jimi.core.raster.JimiRasterImage;
import ij.io.SaveDialog;
//import ij.io.Analyze_Writer;
//import ij.io.BMP_Writer;
import ij.*;
import ij.plugin.filter.PlugInFilter;
import ij.process.*;
import ij.gui.*;
import ij.plugin.frame.PlugInFrame;
import ij.plugin.*;
import ij.plugin.filter.Binary;

import GUI.mainWindow;


public class FileChooser extends JFileChooser {
	
	public static int number = 0;
	public static int numberResult = 0;
	
	public FileChooser() {
	}
	
 	public FileFilter filter = new FileFilter() {
		public boolean accept(File f) {
			if (f.isDirectory()) return true;
		    String name = f.getName().toLowerCase();
		   // System.out.println(name);
		    return name.endsWith("jpg") || name.endsWith("gif") || name.endsWith("bmp") || name.endsWith("png") || name.endsWith("tiff");
	}
		public String getDescription() { return "jpg, gif, bmp, png, tiff"; }
	};	
	
	public static void deleteIntFrame(int number){
		//	System.out.println(number);
		//	System.out.println(FileChooser.number);
		//	if (mainWindow.intFrame[number].type == 0)
			if ( ((internalFrame)(mainWindow.intFrameArrayList.get(number))).type == 0) {
				
				for (int i = 0; i < mainWindow.intFrameArrayList.size(); i++) {
					if ( ((internalFrame)(mainWindow.intFrameArrayList.get(i))).type == 0 )
						if ( ((internalFrame)(mainWindow.intFrameArrayList.get(i))).numberRes > ((internalFrame)(mainWindow.intFrameArrayList.get(number))).numberRes )
							((internalFrame)(mainWindow.intFrameArrayList.get(i))).numberRes--;
				}
				
				mainWindow.numberOpenImages--;
				numberResult--;
			}
			mainWindow.numberImages--;
			
			//((internalFrame)(mainWindow.intFrameArrayList.get(number))).dispose()
			

			
			//mainWindow.intFrameArrayList.remove(number);
			
			for (int i = 0; i < FileChooser.number-1; i++) {
				if (i >= number) {
					//mainWindow.intFrame[i].dispose();
					//System.out.println("POVODNE "+mainWindow.intFrame[i]);
					//((internalFrame)(mainWindow.intFrameArrayList.get(i))).dispose();
					mainWindow.intFrameArrayList.set(i, mainWindow.intFrameArrayList.get(i+1));
					//mainWindow.intFrame[i] = mainWindow.intFrame[i+1];
					//System.out.println("ZMENA "+mainWindow.intFrame[i]);
					((internalFrame)(mainWindow.intFrameArrayList.get(i))).number = ((internalFrame)(mainWindow.intFrameArrayList.get(i+1))).number -1;
					((internalFrame)(mainWindow.intFrameArrayList.get(i))).numberRes = ((internalFrame)(mainWindow.intFrameArrayList.get(i+1))).numberRes;
					//mainWindow.intFrame[i].number = mainWindow.intFrame[i+1].number -1;
					//mainWindow.intFrame[i].number = mainWindow.intFrame[i+1].number;
				}
			}
			FileChooser.number--;
			number--;
			mainWindow.intFrameArrayList.remove(mainWindow.intFrameArrayList.size()-1);
		}	
	
/*	public static void deleteIntFrame(int number){
	//	System.out.println(number);
	//	System.out.println(FileChooser.number);
		if (mainWindow.intFrame[number].type == 0)
			mainWindow.numberOpenImages--;
		mainWindow.numberImages--;
		for (int i = 0; i < FileChooser.number-1; i++) {
			if (i >= number) {
				//mainWindow.intFrame[i].dispose();
				//System.out.println("POVODNE "+mainWindow.intFrame[i]);
				mainWindow.intFrame[i] = mainWindow.intFrame[i+1];
				//System.out.println("ZMENA "+mainWindow.intFrame[i]);
				mainWindow.intFrame[i].number = mainWindow.intFrame[i+1].number -1;
				//mainWindow.intFrame[i].number = mainWindow.intFrame[i+1].number;
			}
		}
		FileChooser.number--;
		
	}*/
	
 	public boolean openFile () {
 		
		  if (mainWindow.numberOpenImages == 4) { 
			 JOptionPane.showMessageDialog(null, "You can open maximally 4 images!", "Message", JOptionPane.INFORMATION_MESSAGE);
			 return false;
		  }

	      new JFileChooser ();
	      this.setDialogTitle ("Open File");

	      // Choose only files, not directories
	      this.setFileSelectionMode ( JFileChooser.FILES_ONLY);

	      // Start in current directory
	      this.setCurrentDirectory (new File ("pics"));

	      this.setFileFilter (filter);
	      this.setAcceptAllFileFilterUsed(false);

	      // Now open chooser
	      int result = this.showOpenDialog (this);

	      if (result == JFileChooser.CANCEL_OPTION) {
	          return true;
	      } else if (result == JFileChooser.APPROVE_OPTION) {

	    	  Image image = Jimi.getImage((this.getSelectedFile ()).toString());
	    	  ImagePlus imp = new ImagePlus();
	    	  imp.setImage(image);
	    	  mainWindow.intFrameArrayList.add(new internalFrame(this.getSelectedFile ().getName(), imp, number, numberResult, 0, true));
	    	  System.out.println("intArrayList "+mainWindow.intFrameArrayList.size());
	  		 // intFrame[number] = new internalFrame(this.getSelectedFile ().getName(), imp, number, numberResult, 0, true);
			  ///create result internalframe///
			  //mainWindow.intFrameResult[numberResult] = new internalFrame(this.getSelectedFile ().getName(), numberResult);
	  		  try {  
	  			  ((internalFrame)(mainWindow.intFrameArrayList.get(number))).setSelected(true);
	  			 // intFrame[number].setSelected(true);
	  			  
	  		  } catch(Exception e){
	  			  System.out.println("Chyba");
	  		  }
	  		  number ++;
	  		  numberResult++;
	      } else {
	          return false;
	      }
	      return true;
	} // openFile 	
	
/* 	public boolean openFile (internalFrame[] intFrame) {
 		
 		  if (mainWindow.numberOpenImages == 4) { 
 			 JOptionPane.showMessageDialog(null, "You can open maximally 4 images!", "Message", JOptionPane.INFORMATION_MESSAGE);
 			 return false;
 		  }

	      new JFileChooser ();
	      this.setDialogTitle ("Open File");

	      // Choose only files, not directories
	      this.setFileSelectionMode ( JFileChooser.FILES_ONLY);

	      // Start in current directory
	      this.setCurrentDirectory (new File ("pics"));

	      this.setFileFilter (filter);
	      this.setAcceptAllFileFilterUsed(false);

	      // Now open chooser
	      int result = this.showOpenDialog (this);

	      if (result == JFileChooser.CANCEL_OPTION) {
	          return true;
	      } else if (result == JFileChooser.APPROVE_OPTION) {

	    	  Image image = Jimi.getImage((this.getSelectedFile ()).toString());
	    	  ImagePlus imp = new ImagePlus();
	    	  imp.setImage(image);
	  		  intFrame[number] = new internalFrame(this.getSelectedFile ().getName(), imp, number, numberResult, 0, true);
  			  ///create result internalframe///
  			  //mainWindow.intFrameResult[numberResult] = new internalFrame(this.getSelectedFile ().getName(), numberResult);
	  		  try {  
	  			  intFrame[number].setSelected(true);
	  			  
	  		  } catch(Exception e){
	  			  System.out.println("Chyba");
	  		  }
	  		  number ++;
	  		  numberResult++;
	      } else {
	          return false;
	      }
	      return true;
 	} // openFile 
*/ 	
 	 	
 	  public static boolean writeFile (File f, ImagePlus imp) {
 		 try {
 			  // File f = new File("myimage.jpg");
 			   JimiRasterImage jrf = Jimi.createRasterImage(imp.getImage().getSource());
 			   Jimi.putImage("image/png",jrf,new FileOutputStream(f));
 			   }
 			catch (Exception je) {
 			   je.printStackTrace();}
 		    return true;
 		  } // writeFile 	
 	
    public boolean saveFile (JInternalFrame Frame, ImagePlus imp) {
        File file = null;
        JFileChooser fc = new JFileChooser ();

        // Start in current directory
        fc.setCurrentDirectory (new File ("pics"));

        // Set filter for Java source files.
        fc.setFileFilter (filter);

        // Set to a default name for save.
        File f = new File("myimage.png");
        
        fc.setSelectedFile (f);

        // Open chooser dialog
        int result = fc.showSaveDialog (this);

        if (result == JFileChooser.CANCEL_OPTION) {
            return true;
        } else if (result == JFileChooser.APPROVE_OPTION) {
            f = fc.getSelectedFile ();
            if (f.exists ()) {
                int response = JOptionPane.showConfirmDialog (null,
                  "Overwrite existing file?","Confirm Overwrite",
                   JOptionPane.OK_CANCEL_OPTION,
                   JOptionPane.QUESTION_MESSAGE);
                if (response == JOptionPane.CANCEL_OPTION) return false;
            }
            System.out.println(f.toString());
            return writeFile (f, imp);
        } else {
          return false;
        }
     } // saveFile 	
     
 	
/* 	public void saveFile (JInternalFrame Frame, ImagePlus imp) {
 		
 //		SaveDialog sd = new SaveDialog("Save as..", Frame.getTitle(), "jpg");
 		Analyze_Writer aw = new Analyze_Writer(imp);
 		aw.run(Frame.getTitle());
 		aw.save(imp, "pics", Frame.getTitle());
 		System.out.println("Hurra");
 		BMP_Writer bw = new BMP_Writer();
 		System.out.println("Hurra");
 		bw.setup("", imp);
 		
 		ImageProcessor ip = imp.getProcessor();
 		bw.run(ip);
 		
 	
	      new JFileChooser ();
	      this.setDialogTitle ("Save file as");

	      // Choose only files, not directories
	      this.setFileSelectionMode ( JFileChooser.FILES_ONLY);

	      // Start in current directory
	      this.setCurrentDirectory (new File ("pics"));
          
	      this.setFileFilter (filter);
	      this.setAcceptAllFileFilterUsed(false);
 
          this.setSelectedFile( new File(Frame.getTitle()) );
          
          int choice = this.showSaveDialog(Frame);
          
          if( choice == JFileChooser.APPROVE_OPTION ) 
          {
            File file = this.getSelectedFile();
            if (filter.accept(file)) {
            	Iterator writers = ImageIO.getImageWritersByFormatName("jpg");
    			ImageWriter writer = (ImageWriter)writers.next();
//    			 Prepare output file
    		//	OutputStream out = new FileOutputStream(file.getPath());
    			//ImageOutputStream ios = ImageIO.createImageOutputStream(out);
    			writer.setOutput(file);			
            	
            } else {
            	JOptionPane.showMessageDialog(this, "Nespravny typ suboru", "Správa", JOptionPane.INFORMATION_MESSAGE);
            	//saveFile(Frame);
            }
//	     	String gr_data = graph.toString();
			try {
				BufferedWriter out = new BufferedWriter(new FileWriter(file));
				//out.write(gr_data);
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
            //this is where a real application would save the file.
          }      
          
          int choice = fileChooser.showSaveDialog(JSVGViewerFrame.this);
          if (choice == JFileChooser.APPROVE_OPTION) {

          fileChooser.setFileHidingEnabled(false);
          fileChooser.setFileSelectionMode
              (JFileChooser.FILES_ONLY);
            fileChooser.addChoosableFileFilter(new ImageFileFilter(".tiff"));

          int choice = fileChooser.showSaveDialog(JSVGViewerFrame.this);
          if (choice == JFileChooser.APPROVE_OPTION) {

      public void handleElement(Element elt, Object data){
      }	      

	} // saveFile 	
*/
}

