package bicat.gui.window;

/**
 *
 * @author Hamed
 */



import bicat.GO.GeneMergeForGO;
import bicat.util.*;
import bicat.gui.*;
import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;



/**
 * Pop-up window that prompts user for search parameters.
 * 
 * Gets user input for a search of the bicluster list.
 * 
 */
public class RunDialog_GOAnalysis implements ActionListener {

	JDialog dialog;

	BicatGui owner;

	public final String GO_WINDOW_APPLY = "start_GO";

	public final String GO_WINDOW_CANCEL = "cancel_GO";
        
        	public final String GO_WINDOW_SELECT_BC_LIST = "select_BC_list";

	static int list_idx = 0;

	static int which_list = -1; // 0 def BCs, 1 def Search Results, ...

	static int which_data = 0;

	boolean andSearch;

	
        
        JComboBox cb;
        static ButtonGroup radioGroup;
        JRadioButton rb_Bilogical;
        JRadioButton rb_Molecular;
        JRadioButton rb_Cellular;
        int cat_radioIndex=0;
        
        static ButtonGroup pop_radioGroup;
        JRadioButton rb_pop_original;
        JRadioButton rb_pop_Fromfile;
        int pop_radioIndex=0;
        
        static JTextField f_field;
        public static final String LOAD_DATA_WINDOW_BROWSE_DATA_FILE = "ld_browse_file_main";
        private File file;
        final File propFile = new File(System.getProperty("user.home"),".bicat.lastfile");
	final String lastFilePropertyName = "last-file";

	// ===========================================================================
	/**
	 * Basic constructor, requires a handle to governing frame.
	 * 
	 */
	public RunDialog_GOAnalysis(BicatGui o) {
		owner = o;
	}

	// ===========================================================================
	private void updateLabel_ListSelection(String item) {

		int[] info = BicatUtil.getListAndIdx(item);
		which_data = info[2];
		which_list = info[0];
		list_idx = info[1];

		if (info[0] == -1) {
			//System.out.println("Select something! (Canceling)");
			//dialog.setVisible(false);
			//dialog.dispose();
                    JOptionPane.showMessageDialog(null,"Please choose a bicluster list\nin which you would like to perform the Functional Analysis");
		} else {
			owner.updateCurrentDataset(which_data);
		}
	}

	// ===========================================================================
	/**
	 * For <code>ActionListener</code> interface, reacts to user selections
	 * and button clicks in this search window.
	 * 
	 */
	public void actionPerformed(ActionEvent e) {

               
               if (GO_WINDOW_SELECT_BC_LIST.equals(e.getActionCommand())) {
			JComboBox box = (JComboBox) e.getSource();
			String item = (String) box.getSelectedItem();
			updateLabel_ListSelection(item);
		}

		else if (GO_WINDOW_CANCEL.equals(e.getActionCommand())) {
			dialog.setVisible(false);
			dialog.dispose();
		}

		else if (GO_WINDOW_APPLY.equals(e.getActionCommand())) {

			//if (which_list == -1) {
                                if(cb.getSelectedIndex()==0){  //nothing choosed
				JOptionPane.showMessageDialog(null,"Please choose a bicluster list\nin which you would like to perform the Functional Analysis");
			} else {
			
                            //owner.search(which_data, which_list, list_idx, geneStr,chipStr, andSearch);
                            String pop_File="";
                            String goType="";
                            if (pop_radioIndex==0)
                                pop_File=owner.currentDirectoryPath+"//"+owner.GO_DIRECTORY_DATASET+which_data+"//pop.txt";
                            else if (pop_radioIndex ==1)
                                pop_File=f_field.getText();
                            
                            if(cat_radioIndex==0)
                                goType=GeneMergeForGO.GO_BIOLOGICAL_PROCESS;
                            else if(cat_radioIndex==1)
                                goType=GeneMergeForGO.GO_MOLECULAR_FUNCTION;
                            else if (cat_radioIndex==2)
                                goType=GeneMergeForGO.GO_CELLULAR_COMPONENT;
                            
                            // get the corresposnding  cluster list
                            String item = (String)cb.getSelectedItem();
                            LinkedList bcList= owner.getBicListFromLabel(item);
                            // get the bicName;
                            String bicName=BicatUtil.getBicNameFromLabel(item);
                            // call the gene Merge.
                            GeneMergeForGO.createGeneMergeFiles_GOAnalysis(which_data, goType, pop_File,bicName,bcList);
                            
				dialog.setVisible(false);
				dialog.dispose();
			}
		}
                else if (LOAD_DATA_WINDOW_BROWSE_DATA_FILE.equals(e.getActionCommand())) {

			if (BicatGui.debug)
				System.out.println("Current working directory is: "+BicatGui.currentDirectoryPath);

			JFileChooser jfc = new JFileChooser(BicatGui.currentDirectoryPath);
			jfc.setMultiSelectionEnabled(true);
			jfc.setDragEnabled(true);
			jfc.setDialogTitle("Select main data file:");
			try {
				Properties prop = new Properties();
				prop.load(new FileInputStream(propFile));
				if (prop.containsKey(lastFilePropertyName)) {
					File selFile = new File(prop.getProperty(lastFilePropertyName));
					jfc.setSelectedFile(selFile);
				}
			} catch (IOException ex) {
				// could not fetch last file from properties file
				// ignore exception
				ex.printStackTrace();
			}

			if (jfc.showOpenDialog(owner) == JFileChooser.APPROVE_OPTION) {
				file = jfc.getSelectedFile();
				Properties prop = new Properties();
				prop.setProperty(lastFilePropertyName, file.getAbsolutePath());
				try {
					prop.store(new FileOutputStream(propFile),lastFilePropertyName);
				} catch (IOException ex) {
					// ignore
					ex.printStackTrace();
				}
				f_field.setText(file.getPath());
			} else
				return; 
		}
	}

	// ===========================================================================
	/**
	 * Creates the visible pop up window with all buttons, labels and fields.
	 * 
	 */
	public void makeWindow() {

		dialog = new JDialog(owner, "GO Analysis ");

		// ////////////////////////list choice panel////////////////////////////////////////////////////

		JPanel listChoice = new JPanel(new FlowLayout());
		listChoice.setBorder(BorderFactory.createTitledBorder(BorderFactory
				.createLineBorder(Color.GRAY), "Choose list of biclusters"));

		Vector names = owner.getListNamesAll();
		cb = new JComboBox(names);
		cb.setActionCommand(GO_WINDOW_SELECT_BC_LIST);
		cb.setSelectedIndex(0);
		cb.addActionListener(this);
		listChoice.add(cb);

		// ///// GO category panel/////////////////////////////////////////////////////////////////////

		JPanel goCategoryPanel = new JPanel(new GridLayout(0,3));
		goCategoryPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory
				.createLineBorder(Color.GRAY), "Select GO Categories (Default is Biological Process)"));
                
                radioGroup = new ButtonGroup(); 
                rb_Bilogical=new JRadioButton("Biological Process ",true);
                rb_Bilogical.addActionListener(this);
		goCategoryPanel.add(rb_Bilogical);
                
                rb_Molecular=new JRadioButton("Molecular Function ",false);
                rb_Molecular.addActionListener(this);
		goCategoryPanel.add(rb_Molecular);
                
                rb_Cellular=new JRadioButton("Cellular Component ",false);
                rb_Cellular.addActionListener(this);
		goCategoryPanel.add(rb_Cellular);
                
                RadioButtonHandler handler = new RadioButtonHandler();
                rb_Bilogical.addItemListener(handler);
		rb_Molecular.addItemListener(handler);
		rb_Cellular.addItemListener(handler);
                
                radioGroup.add(rb_Bilogical);
                radioGroup.add(rb_Molecular);
                radioGroup.add(rb_Cellular);
                
               // ///////////////// population panel/////////////////////////////////////////////////////////

		JPanel pop_Panel = new JPanel(new GridLayout(0,1));
		JPanel pop_Panel_1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
                JPanel pop_Panel_2 = new JPanel(new FlowLayout());
                
                pop_Panel.setBorder(BorderFactory.createTitledBorder(BorderFactory
				.createLineBorder(Color.GRAY), "Select GO Categories (Default is Biological Process)"));
                
		pop_radioGroup = new ButtonGroup(); 
                rb_pop_original=new JRadioButton("Default Population File inthe Original Data",true);
                rb_pop_original.addActionListener(this);
		
                
                rb_pop_Fromfile=new JRadioButton("From File",false);
                rb_pop_Fromfile.addActionListener(this);
		
                
                RadioButtonHandler_pop handler_pop = new RadioButtonHandler_pop();
                rb_pop_Fromfile.addItemListener(handler_pop);
		rb_pop_original.addItemListener(handler_pop);
		
                pop_radioGroup.add(rb_pop_original);
                pop_radioGroup.add(rb_pop_Fromfile);
                
                
                f_field = new JTextField("C:/TEMP/100_20.txt",23);
				
                JButton browse = new JButton("Browse..");
		browse.setActionCommand(LOAD_DATA_WINDOW_BROWSE_DATA_FILE);
		browse.addActionListener(this);
		
                
                pop_Panel_1.add(rb_pop_original);
               
                
                pop_Panel_2.add(rb_pop_Fromfile);
                pop_Panel_2.add(f_field);
                pop_Panel_2.add(browse);
                
                pop_Panel.add(pop_Panel_1);
                pop_Panel.add(pop_Panel_2);
                  
                ///////////////////////// Button panel////////////////////////////////////////////////////
                      
                JPanel buttonPanel = new JPanel(new FlowLayout());       
                JButton okayButton = new JButton("Run GO Analysis");
		okayButton.setMnemonic(KeyEvent.VK_K);
		okayButton.setActionCommand(GO_WINDOW_APPLY);
		okayButton.addActionListener(this);
		buttonPanel.add(okayButton);

		JButton cancelButton = new JButton("Cancel");
		cancelButton.setMnemonic(KeyEvent.VK_C);
		cancelButton.setActionCommand(GO_WINDOW_CANCEL);
		cancelButton.addActionListener(this);
		buttonPanel.add(cancelButton);

		
             
                

		// //////////////////// add all panels//////////////////////////////////////////////////////
		JPanel contentPane = new JPanel(new GridLayout(0, 1,0,20));

		contentPane.add(listChoice);
		contentPane.add(goCategoryPanel);
                contentPane.add(pop_Panel);
		contentPane.add(buttonPanel);

		contentPane.setOpaque(true);
		dialog.setContentPane(contentPane);

		// set size, location and make visible
		dialog.pack();
		dialog.setLocationRelativeTo(owner);
		dialog.setVisible(true);
	}

        
         //Creates class to handle buttons and assigns if/else tasks
public class RadioButtonHandler implements ItemListener
 
	{
 			public void itemStateChanged(ItemEvent event)
 				{
 
					if (event.getSource() == rb_Bilogical )
					cat_radioIndex = 0;
 
					else if(event.getSource() == rb_Molecular)
					cat_radioIndex = 1;
 
					else if(event.getSource() == rb_Cellular)
					cat_radioIndex = 2;
 		
                        System.out.println("cat_radioIndex <<"+cat_radioIndex);
                              }
  }
        
 public class RadioButtonHandler_pop implements ItemListener
 
	{
 			public void itemStateChanged(ItemEvent event)
 				{
 
					if (event.getSource() == rb_pop_original )
					pop_radioIndex = 0;
 
					else if(event.getSource() == rb_pop_Fromfile)
					pop_radioIndex = 1;
                                        
                                        System.out.println("pop_radioIndex <<"+pop_radioIndex);
 
                              }
                   
  }       
}
