//
// Core Program for TETDM 
// Control.java Version 0.32 
// Copyright(C) 2011 2012 TETDM CORE MEMBER ALL RIGHTS RESERVED. 
// This program is provided under the license.
//


package source;

import source.TextData.*;


import java.awt.*;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.*;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.border.BevelBorder;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;


import java.awt.Graphics;
import java.awt.Graphics2D;

//Control panel :YELLOW
public class Control extends JPanel implements ActionListener, ComponentListener
{
	MainFrame mainframe;
	final int MAX_PANEL = 10;
	int defaultPanelNumber = 2;
	int panelNumber = 0;
	int defaultPanelSizeX, defaultPanelSizeY;
	boolean first = true;
	
	JPanel upperPanel;//upper select and setting panel
	CardLayout layout;
	
	JSplitPane splitpane[];

	String settingFile;	
	SettingData sp1;
	
	SettingPanel settingPanel;
	JPanel selectPanel;	//panel for modules
	
	Select panel[];
	Select stealthPanel;
	
	JPanel buttonPanel;	//lower button panel

	JButton bt10 = new JButton();
	JButton bt20 = new JButton();
	JButton bt30 = new JButton();
	JButton bt40 = new JButton();
	JButton bt50 = new JButton();
	JButton bt99 = new JButton();
	JButton bt52 = new JButton();	
	JButton bt55 = new JButton();	
	JButton bt60 = new JButton();
	JButton bt70 = new JButton();	
	JToggleButton bt0 = new JToggleButton();	
	
	String buttonNamesInEnglish[] = {"Reload text and Restructure", "FontSize--", "FontSize++", "Add Panel", "Reduce Panel", 
										"Quit", "Load Directory", "Load New File", "Add New File Data", "Save Combination", "Settings"};
	String buttonNamesInJapanese[];
	String inJapanese[] = new String[2];
	
	ModuleData moduleData;

	//TEXT DATA
	String original_file="", read_filename;
	boolean textLoaded = false;	
	TextData text;

	String absolutePath;

	public Control(MainFrame mainf, String file, String absolute)
	{
		mainframe = mainf;
		absolutePath = absolute;

		setBackground(Color.white);
		
		splitpane = new JSplitPane[MAX_PANEL];
		
		addComponentListener(this);
		
		//Panel Creation 1
		setLayout(new BorderLayout());		
		layout = new CardLayout();
		upperPanel = new JPanel(layout);
		add(upperPanel);
		
		selectPanel = new JPanel(new GridLayout());
		upperPanel.add(selectPanel, "select");
		
		
		//Data Settings
		moduleData = new ModuleData(absolutePath);	
		
		settingFile = absolutePath + "tetdm.conf";
		sp1 = new SettingData(settingFile, moduleData);		
		
		moduleData.initializeVisualiationModuleSelection();		
		moduleData.initializeModuleSubset();
		
		if(sp1.panels > 0)
			panelNumber = sp1.panels;
		else
			panelNumber = defaultPanelNumber;

		//Panel Creation 2		
		settingPanel = new SettingPanel(sp1);
		upperPanel.add(settingPanel, "setting");
		
		panel = new Select[MAX_PANEL];

		readJapaneseLabels();
		initializeButtonPanel();
	
		if(!file.equals(""))
		{
			textDataLoading(file);
			initializeSelectPanel();
		}
		else 
		{			
			GuidancePanel gp = new GuidancePanel();
			selectPanel.add(gp);
			initialButtonSet(false);
		}
	}
	
	void calculateDefaultPanelSizeInitial(int panelNum)
	{
		if(panelNum == 1)
			defaultPanelSizeX = mainframe.windowSizeX;
		else
			defaultPanelSizeX = (mainframe.windowSizeX - (11*(panelNum-1)))/panelNum;

		defaultPanelSizeY = mainframe.windowSizeY - 194;		
	}
	
	void calculateDefaultPanelSize(int panelNum)
	{
		if(panelNum == 1)
			defaultPanelSizeX = getWidth();
		else
			defaultPanelSizeX = (getWidth() - (11*(panelNum-1)))/panelNum;
		
		defaultPanelSizeY = getHeight() - 194;		
	}	

	class GuidancePanel extends JPanel
	{
		Toolkit tk = getToolkit();
		public Image image1 = tk.getImage(absolutePath+"source"+File.separator+"tet1208moto.gif");
		
		public void paintComponent(Graphics g)
		{
			Graphics2D g2 = (Graphics2D)g;
			int sizex = getWidth();
			int sizey = getHeight();
			
			g2.setColor(new Color(0,128,255));
			g2.fillRect(0,0, sizex, sizey);
			
			g2.drawImage(image1,0,0,this);
			
			g2.setColor(Color.yellow);
			g2.setFont(new Font("Dialog", Font.BOLD, 20));
			
			if(sp1.inJapanese)
				g2.drawString(buttonNamesInJapanese[12],sizex-500,sizey-50);				
			else
				g2.drawString("Push [Load New File] Button!",sizex-500,sizey-50);
		}
	}

	void textDataLoading(String loadFile)
	{
		//TEXT READ
		original_file = loadFile;		//Original text file
		read_filename = loadFile+"2";	//Copied text file
		EXECUTE.filecopy(loadFile, read_filename);	//make copy, ALL procedures only for this copy			
		
		textDataLoadingWithoutCopy();
		
		textLoaded = true;
	}
	
	void textDataLoadingWithoutCopy()
	{
		String source_filename = new File(read_filename).getAbsolutePath();
		String chafile = source_filename + ".cha";
		String ext = "";
		
		int point = source_filename.lastIndexOf(".");
		if (point != -1) 
		{
			ext = source_filename.substring(point + 1);
		}		
		
		if(ext.equals("csv2"))
		{
			Makecha makecha = new Makecha(source_filename, absolutePath);
		}		
		else if(sp1.isEnglish)
		{
//			Makecha makecha = new Makecha(source_filename, sp1.isWindows);
			Makecha makecha = new Makecha(source_filename);
		}
		else
			EXECUTE.exe_chasen(sp1.chasenexe, source_filename, chafile, sp1.isWindows, sp1.chasenPath);

		text = new TextData(source_filename, chafile, sp1, absolutePath, this);
	}	

	void setSplitDivider(int n)
	{
		int divideLine = defaultPanelSizeX * (n+1);
		if(n > 0)
			divideLine += 11 * (n - 1);
		splitpane[n].setDividerLocation(divideLine);		
	}
	
	void setPanels()
	{
		if(panelNumber == 1)
			selectPanel.add(panel[0]);
		else
		{
			for(int i=0;i<panelNumber-1;i++)
			{
				splitpane[i] = new JSplitPane();
				splitpane[i].setOneTouchExpandable(true);
				splitpane[i].setContinuousLayout(true);				
				
				setSplitDivider(i);
				
				splitpane[i].setRightComponent(panel[i+1]);
				if(i==0)
					splitpane[0].setLeftComponent(panel[0]);
				else
					splitpane[i].setLeftComponent(splitpane[i-1]);
			}
			selectPanel.add(splitpane[panelNumber-2]);
		}
	}
	
	void initializeSelectPanel()
	{
		if(first)
		{
			calculateDefaultPanelSizeInitial(panelNumber);	
			first = false;
		}
		else
			calculateDefaultPanelSize(panelNumber);		

		stealthPanel = new Select(text, 10000, moduleData, inJapanese, defaultPanelSizeX, defaultPanelSizeY);
		
		for(int i=0;i<panelNumber;i++)
		{
			panel[i] = new Select(text, i, moduleData, inJapanese, defaultPanelSizeX, defaultPanelSizeY);
			panel[i].setMinimumSize(new Dimension(0,0));
			panel[i].changePanel(sp1.miningID[i],sp1.visualizationID[i]);			
		}
		
		setPanels();
	}
	
	//ADD PANEL
	public void addNewPanel()
	{
		if(panelNumber > MAX_PANEL - 1)
			return;		
		
		calculateDefaultPanelSize(panelNumber+1);
		panel[panelNumber] = new Select(text, panelNumber, moduleData, inJapanese, defaultPanelSizeX, defaultPanelSizeY);
		panel[panelNumber].setMinimumSize(new Dimension(0,0));
		
		splitpane[panelNumber-1] = new JSplitPane();
		
		for(int i=0;i<panelNumber;i++)
			setSplitDivider(i);			

		
		splitpane[panelNumber-1].setRightComponent(panel[panelNumber]);
		
		if(panelNumber == 1)
		{
			selectPanel.remove(panel[0]);
			splitpane[0].setLeftComponent(panel[0]);
		}
		else
		{
			selectPanel.remove(splitpane[panelNumber-2]);			
			splitpane[panelNumber-1].setLeftComponent(splitpane[panelNumber-2]);
		}
		
		selectPanel.add(splitpane[panelNumber-1]);
		selectPanel.revalidate();			
		panelNumber++;
	}	
	
	//DELETE PANEL
	void deleteSplitPane(int deleteNumber)
	{
		for(int i=deleteNumber;i<panelNumber-2;i++)
			splitpane[i] = splitpane[i+1];
	}
	
	void deletePanel(int deleteNumber)
	{
		for(int i=deleteNumber;i<panelNumber-1;i++)
		{
			panel[i] = panel[i+1];
			panel[i].setPanelID(i);
			panel[i].setTitle2();
		}
		panelNumber--;		
	}

	void delete(int deleteNumber)
	{
		if(panelNumber == 1 || deleteNumber >= panelNumber || deleteNumber < 0)
			return;	
		
		calculateDefaultPanelSize(panelNumber-1);		
		
		selectPanel.remove(splitpane[panelNumber-2]);		
		for(int i=0;i<panelNumber-1;i++)
			splitpane[i].removeAll();
		
		deletePanel(deleteNumber);

		setPanels();		
		selectPanel.revalidate();		
	}	

	
	
    void initialButtonSet(boolean check)
    {
		bt10.setEnabled(check);
		bt20.setEnabled(check);
		bt30.setEnabled(check);
		bt40.setEnabled(check);
		bt50.setEnabled(check);
		bt60.setEnabled(check);
		bt70.setEnabled(check);
    }

	void initializeButtonPanel()
	{
		buttonPanel = new JPanel(new GridLayout());		
		buttonPanel.setBackground(Color.YELLOW);

		bt10.setBackground(Color.YELLOW);
		bt10.addActionListener(this);
		buttonPanel.add(bt10);
		
		bt20.setBackground(Color.YELLOW);
		bt20.addActionListener(this);
		buttonPanel.add(bt20);
		
		bt30.setBackground(Color.YELLOW);
		bt30.addActionListener(this);
		buttonPanel.add(bt30);

		bt40.setBackground(Color.YELLOW);
		bt40.addActionListener(this);
		buttonPanel.add(bt40);		

		bt50.setBackground(Color.YELLOW);		
		bt50.addActionListener(this);
		buttonPanel.add(bt50);

		bt99.setBackground(Color.YELLOW);		
        bt99.addActionListener(this);
		buttonPanel.add(bt99);
		
		bt52.setBackground(Color.YELLOW);		
		bt52.addActionListener(this);
		buttonPanel.add(bt52);		
		
		bt55.setBackground(Color.YELLOW);		
		bt55.addActionListener(this);
		buttonPanel.add(bt55);		
		
		bt60.setBackground(Color.YELLOW);		
		bt60.addActionListener(this);
		buttonPanel.add(bt60);
		
		bt70.setBackground(Color.YELLOW);		
		bt70.addActionListener(this);
		buttonPanel.add(bt70);
		
		bt0.setBackground(Color.YELLOW);		
		bt0.addActionListener(this);
		buttonPanel.add(bt0);

		add(buttonPanel, BorderLayout.SOUTH);

		setButtonLabel();
	}
	
	public void readJapaneseLabels()
	{
		String filename = absolutePath + "Japanese.txt";
		File jpname = new File(filename);
		buttonNamesInJapanese = FILEIO.TextFileAllReadCodeArray(jpname);
		inJapanese[0] = buttonNamesInJapanese[11];
		inJapanese[1] = buttonNamesInJapanese[15];		
	}
	
	public void setButtonLabel()
	{
		if(sp1.inJapanese)
		{
			bt10.setText(buttonNamesInJapanese[0]);
			bt20.setText(buttonNamesInJapanese[1]);
			bt30.setText(buttonNamesInJapanese[2]);
			bt40.setText(buttonNamesInJapanese[3]);
			bt50.setText(buttonNamesInJapanese[4]);
			bt99.setText(buttonNamesInJapanese[5]);
			bt52.setText(buttonNamesInJapanese[6]);			
			bt55.setText(buttonNamesInJapanese[7]);
			bt60.setText(buttonNamesInJapanese[8]);
			bt70.setText(buttonNamesInJapanese[9]);			
			bt0.setText(buttonNamesInJapanese[10]);
		}
		else
		{
			bt10.setText(buttonNamesInEnglish[0]);
			bt20.setText(buttonNamesInEnglish[1]);
			bt30.setText(buttonNamesInEnglish[2]);
			bt40.setText(buttonNamesInEnglish[3]);
			bt50.setText(buttonNamesInEnglish[4]);
			bt99.setText(buttonNamesInEnglish[5]);
			bt52.setText(buttonNamesInEnglish[6]);
			bt55.setText(buttonNamesInEnglish[7]);
			bt60.setText(buttonNamesInEnglish[8]);
			bt70.setText(buttonNamesInEnglish[9]);
			bt0.setText(buttonNamesInEnglish[10]);			
		}
	}
	
	public void resetSelectpanelData()
	{		
		stealthPanel.resetAll_for_stealth(text);	//FOR reset moduleData
		
		for(int i=0;i<panelNumber;i++)
			panel[i].resetAll(text);
	}
	
/*	
	//FOCUS	
	public void setDisplayOthersByTouchFocus(int panelID)
	{
		for(int i=0;i<panelNumber;i++)
			if(i != panelID)
				panel[i].setDisplayByTouchFocus();
	}
	//FOCUS	
	public void setDisplayOthersByClickFocus(int panelID)
	{
		for(int i=0;i<panelNumber;i++)
			if(i != panelID)
				panel[i].setDisplayByClickFocus();
	}
	//FOCUS
	public void resetSelectPanelDataByTouchFocus(int panelID)
	{
		for(int i=0;i<panelNumber;i++)
		    if(i != panelID)
				panel[i].resetMiningByTouchFocus();
	}
	//FOCUS
	public void resetSelectPanelDataByClickFocus(int panelID)
	{
		for(int i=0;i<panelNumber;i++)
		    if(i != panelID)
				panel[i].resetMiningByClickFocus();
	}
	//FOCUS	ALL
	public void resetSelectPanelDataByTouchFocusAll(int panelID)
	{
		panel[panelID].resetMiningByTouchFocus();		
		resetSelectPanelDataByTouchFocus(panelID);
	}	
	//FOCUS	ALL
	public void resetSelectPanelDataByClickFocusAll(int panelID)
	{
		panel[panelID].resetMiningByClickFocus();
		resetSelectPanelDataByClickFocus(panelID);
	}	
*/	
	//FOCUS	
	public void setDisplayOthersByTouchFocus(int panelID)
	{
		for(int i=0;i<panelNumber;i++)
			if(i != panelID)
				panel[i].setDisplayByTouchFocus();
	}
	//FOCUS	
	public void setDisplayOthersByClickFocus(int panelID)
	{
		for(int i=0;i<panelNumber;i++)
			if(i != panelID)
				panel[i].setDisplayByClickFocus();
	}
	//FOCUS
	public void resetSelectPanelDataByTouchFocus(int panelID)
	{
		for(int i=0;i<panelNumber;i++)
		    if(i != panelID)
				panel[i].resetMiningByTouchFocus();
	}
	//FOCUS
	public void resetSelectPanelDataByClickFocus(int panelID)
	{
		for(int i=0;i<panelNumber;i++)
		    if(i != panelID)
				panel[i].resetMiningByClickFocus();
	}
	//FOCUS	ALL
	public void resetSelectPanelDataByTouchFocusAll(int panelID)
	{
		panel[panelID].resetMiningByTouchFocus();		
		resetSelectPanelDataByTouchFocus(panelID);
	}	
	//FOCUS	ALL
	public void resetSelectPanelDataByClickFocusAll(int panelID)
	{
		panel[panelID].resetMiningByClickFocus();
		resetSelectPanelDataByClickFocus(panelID);
	}
	
	
	
	public void resetFontSize()
	{
		for(int i=0;i<panelNumber;i++)
			panel[i].reset_font_size();
	}
	
	
	//FOR MODULE EXECUTION
	public int findModule(int moduleID, boolean flags[])
	{
		for(int i=0;i<panelNumber;i++)
		{
//			System.out.println(i+":"+moduleID+"ID:panelmoduleID "+panel[i].miningIDs[panel[i].selected_module]);
			
			if(panel[i].miningIDs[panel[i].selected_module] == moduleID && flags[i] == false)
				return i;
			
		}
		
		return -1;
	}
	
	public int findVisualizationModule(int visuModuleID, boolean flags[])
	{
		for(int i=0;i<panelNumber;i++)
		{
//			System.out.println(i+":"+visuModuleID+"ID:panelmoduleID "+panel[i].visualizationIDs[panel[i].pair_visu[panel[i].selected_module]]);
			
			if(panel[i].visualizationIDs[panel[i].pair_visu[panel[i].selected_module]] == visuModuleID && flags[i] == false)
				return i;
		}
		
		return -1;
	}	
	
	public boolean fileChoose()
	{
		JFileChooser fc = new JFileChooser(absolutePath+File.separator+"text");
		FileFilter filter1;
		FileFilter filter2;		
		
		
		if(sp1.inJapanese)
		{
			filter1 = new FileNameExtensionFilter(buttonNamesInJapanese[13], "txt");
			filter2 = new FileNameExtensionFilter(buttonNamesInJapanese[14], "txt");
		}
		else 
		{
			filter1 = new FileNameExtensionFilter("Text in Japanese", "txt");
			filter2 = new FileNameExtensionFilter("Text in English", "txt");
		}

		fc.addChoosableFileFilter(filter2);
		fc.addChoosableFileFilter(filter1);
		
		int selected = fc.showOpenDialog(this);
		
		if (selected != JFileChooser.APPROVE_OPTION)
			return false;

		File inputFile = fc.getSelectedFile();
		original_file = inputFile.getAbsolutePath();
			
		if(fc.getFileFilter().getDescription().equals(filter2.getDescription()))
			sp1.isEnglish = true;
		else
			sp1.isEnglish = false;

		return true;
	}
	
	public boolean fileChooseFromDirectory()
	{
		JFileChooser fc = new JFileChooser(absolutePath);
		fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);	
		
		int selected = fc.showOpenDialog(this);
		
		if (selected != JFileChooser.APPROVE_OPTION)
			return false;
		
		File inputFile = fc.getSelectedFile();
		original_file = FILEIO.makeOne(inputFile,absolutePath,sp1.defaultCode,sp1.segment_tag);
		
		return true;
	}	

	public void panelSet(int moduleIDs[], int displayIDs[])
	{
		panelNumber = moduleIDs.length;

		sp1.setModulesToPanels(moduleIDs,displayIDs);
		panelsReConstruction();
		
//		settingPanel.initializeCheckBox();
//		settingPanel.initializeCheckBox2();		

		layout.show(upperPanel, "select");
	}
	
	public void panelSetByMiningModule(int moduleID)
	{
		int rID = moduleData.findModule(moduleID);
		
		panelSet(moduleData.miningPanelSet[rID].MiningIDs, moduleData.miningPanelSet[rID].VisualizationIDs);
	}	

	public void backPanelSetByMiningModule(int moduleID)
	{
		int rID = moduleData.findModule(moduleID);
		
		panelSet(moduleData.miningPanelSet[rID].backMiningIDs, moduleData.miningPanelSet[rID].backVisualizationIDs);
	}	
	
	//Action listener
	public void actionPerformed(ActionEvent e)
	{
		if(e.getSource() == bt10)
		{
			if(!textLoaded)
				return;
			
			textDataLoadingWithoutCopy();/////
			resetSelectpanelData();
		}
		
		if(e.getSource() == bt20)
		{			
			if(text.fontSize > 1)
				text.fontSize--;
			resetFontSize();
		}
		
		if(e.getSource() == bt30)
		{
			if(text.fontSize < 100)
				text.fontSize++;
			resetFontSize();
		}		

		if(e.getSource() == bt40)
		{
			if(!textLoaded)
				return;
			
			addNewPanel();
		}			
		
		if(e.getSource() == bt50)
		{
			delete(panelNumber-1);
		}
		
		if(e.getSource() == bt99)//Quit application
		{
			mainframe.dispose(); //destroy frame
			System.exit(0);
		}		

		if(e.getSource() == bt52)
		{
			if(!fileChooseFromDirectory())
				return;
			
			if(textLoaded == false)
			{			
				textDataLoading(original_file);				
				panelsReConstruction();
				initialButtonSet(true);
			}
			else
			{
				textDataLoading(original_file);
				resetSelectpanelData();
			}
			
			layout.show(upperPanel, "select");
			
			
		}		
		
		if(e.getSource() == bt55)
		{
			if(!fileChoose())
				return;
			
			if(textLoaded == false)
			{			
				textDataLoading(original_file);			
				panelsReConstruction();
				initialButtonSet(true);
			}
			else
			{
				textDataLoading(original_file);
				resetSelectpanelData();
			}
			
			layout.show(upperPanel, "select");			
		}		

		if(e.getSource() == bt60)
		{
			if(!fileChoose())
				return;
			
			textDataLoading(original_file);
			
		    // TODO show dialog for preprocessing for text file
			//		    TextLoader tl = new TextLoader(original_file,isEnglish);
		    // TODO avoid from opening more than two files
			//		    text = tl.getTextData();
			
			addNewPanel();
		}	
		
		if(e.getSource() == bt70)
		{
			sp1.panels = panelNumber;
			for(int i=0;i<panelNumber;i++)
			{
				sp1.miningID[i] = moduleData.msub.selectedMiningIDs[panel[i].selected_module];
				sp1.visualizationID[i] = moduleData.msub.selectedVisualizationIDs[panel[i].pair_visu[panel[i].selected_module]];
				sp1.saveSettingFile();
//				System.out.println(moduleData.msub.selectedMiningIDs[panel[i].selected_module] +":"
//								   +moduleData.msub.selectedVisualizationIDs[panel[i].pair_visu[panel[i].selected_module]]);
			
			}	
		}
		
		if(e.getSource() == bt0)//Setting Panel
		{

			
			if(bt0.isSelected())
			{
				settingPanel.setData();
				settingPanel.setDisplay();
				layout.show(upperPanel, "setting");
				
				settingPanel.setChanged(false);
				settingPanel.setTextReset(false);				
			}
			else
			{
				if(!textLoaded)
				{
					layout.show(upperPanel, "select");					
				}
				else
				{
					if(settingPanel.textReset)	// Reset TextData
					{
						textDataLoadingWithoutCopy();/////
						resetSelectpanelData();
					
						settingPanel.setTextReset(false);
					}
				
					if(settingPanel.isChanged)	// Reconstruct Panels
					{
						moduleData.initializeModuleSubset();					
						panelsReConstruction();
						settingPanel.setChanged(false);		// for settingPanel Flag
						setButtonLabel();					// for English Menu
					}
					layout.show(upperPanel, "select");					
				}
			}
		}
	}
	
	//ComponentListener
	public void componentHidden(ComponentEvent e){}
	public void componentMoved(ComponentEvent e){}
	public void componentShown(ComponentEvent e){}
	public void componentResized(ComponentEvent e)
	{
		if(!textLoaded)
			return;		
		
		calculateDefaultPanelSize(panelNumber);
		for(int i=0;i<panelNumber-1;i++)
			setSplitDivider(i);		
	}	
	
	void panelsReConstruction()
	{
		upperPanel.remove(selectPanel);
		selectPanel = new JPanel(new GridLayout());
		upperPanel.add(selectPanel, "select");
		initializeSelectPanel();
		upperPanel.revalidate();		
	}
	
}

