//modified on Oct. 14,2013.
//
// Visuzalization module for TETDM 
// SampleDisplay.java Version 0.30 
// This is one of the sample modules.
// You should read the README file.
//

package module.VisualizationModules.TermDisplay;

import source.*;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.ArrayList;

import javax.swing.*;


@SuppressWarnings("serial")
public class TermDisplay extends VisualizationModule implements ActionListener
{
	// Panels
	@SuppressWarnings("rawtypes")
	JList list;
	@SuppressWarnings("rawtypes")
	DefaultListModel model;
	JLabel l1,l2,l3;
	JButton button1, button2;
	String lText[];
	int[] count; // for counting # of words per status
	int total;

	// Others
	boolean dataFlg;

	String termArray[];
	int valArray[];
	ArrayList<Integer> status; // Status of word: 0..unchecked, 1..good, 2..bad

	String outputFileName;

	
	
	public TermDisplay()
	{
		setModuleID(25);			// Set your module ID after you have got it
		setCategoryID(4);
        
        dataNumbers = new int[]{0,0,0,0,    // b,i,d,S	String 1+
            0,1,0,1,    // bA,iA,dA,SA					doubleArray 1+
            0,0,0};     // bA2,iA2,dA2
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void initializePanel()
	{
		JPanel p = new JPanel();
		p.setLayout(new GridLayout(1,4));
		button1 = new JButton("UpdateDic");
		button2 = new JButton("ResetDic");
		lText = new String[3];
		lText[0]="Unchecked";
		lText[1]="Good";
		lText[2]="Bad";
		count = new int[3];
		count[0]=0;
		count[1]=0;
		count[2]=0;
		total = 0;
		l1 = new JLabel();
		setLabel(l1,1);
		l1.setOpaque(true);
		l1.setBackground(Color.red);
		l2 = new JLabel();
		setLabel(l2,2);
		l2.setOpaque(true);
		l2.setBackground(Color.gray);
		l3 = new JLabel();
		setLabel(l3,0);
		l3.setOpaque(true);
		l3.setBackground(Color.white);
		p.add(button1);
		p.add(button2);
		p.add(l1);
		p.add(l2);
		p.add(l3);
		add(p,BorderLayout.SOUTH);
		JScrollPane scroll1 = new JScrollPane();
		JViewport view = scroll1.getViewport();
		add(scroll1,BorderLayout.CENTER);
		button1.addActionListener(this);
		button2.addActionListener(this);
		model = new DefaultListModel();	
		list = new JList(model);
		view.setView(list);
		MyCellRenderer renderer = new MyCellRenderer();
		list.setCellRenderer(renderer);
		MouseListener mouseListener = new MouseAdapter(){
			public void mouseClicked(MouseEvent e){
				DoOperationClicked();
				if(e.getClickCount()>=2){ // Double click causes status change.
					DoOperationDoubleClicked();
				}
			}
		};
		list.addMouseListener(mouseListener);
    }
	
	public void initializeData()
	{
/*		try {			
			File fp = new File(myModulePath + "settings.txt");
			BufferedReader br = new BufferedReader(
					new InputStreamReader(new FileInputStream(fp)));
			outputFileName = br.readLine();
			br.close();
		} catch(Exception e){
//			e.printStackTrace();
			outputFileName="AddWords.csv";
		} */
		outputFileName = "AddWords.csv";
		dataFlg = false;
		status = new ArrayList<Integer>();
		count[0]=0;
		count[1]=0;
		count[2]=0;
		total = 0;
		setLabel(l1,1);
		setLabel(l2,2);
		setLabel(l3,0);
		termArray = new String[1];
		termArray[0] = "None";
		valArray = new int[1];
		valArray[0] = -1;
	}
	
	public void displayOperations(int optionNumber)
	{
		switch(optionNumber)
		{
			case 0:
				if(!dataFlg){ // data not sent from mining module
					model.clear();
				}
				break;
		}		
	}

	@SuppressWarnings("unchecked")
	public boolean setData(int dataID, String data[]) // receive word list
	{
		switch(dataID)
		{
			case 0: 
				model.clear();
				termArray = data;
				for(int i=0;i<termArray.length;i++){
					model.addElement(new String(termArray[i]));
				status.add(0);
				count[0]++;
				total++;
				}
				dataFlg = true;
				setLabel(l1,1);
				setLabel(l2,2);
				setLabel(l3,0);
				return true;
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	public boolean setData(int dataID, int data[]) // receive value corresponding to words
	// Notice: This should be called only after setData(int id, String[] tlist)
	{
		switch(dataID)
		{
			case 0:
				if(!dataFlg) {
					return false;
				}
				valArray = data;
				if(valArray.length!=termArray.length){ // do nothing if # of values and words are different.
					return false;
				}
				for(int i=0;i<termArray.length;i++){
					model.set(i,termArray[i]+" ["+valArray[i]+"]");
				}
				return true;
		}
		return false;
	}
	
	private void setLabel(JLabel label, int idx)
	{
		double ratio;
		if(total==0){
			ratio = 0;
		} else {
			ratio = (double)count[idx] / total;
		}
		String str = String.format("%s: %d (%.3f)", lText[idx], count[idx], ratio);
		label.setText(str);
	}
	
	protected void DoOperationClicked() // change focused keyword
	{
		System.out.println(list.getSelectedIndex());
		setMainFocusString(termArray[list.getSelectedIndex()]);
		setMainFocusKeyword(getKeywordID(),true);
		repaintOthersByFocus();
		executeOthersByFocus();
	}
	
	protected void DoOperationDoubleClicked() { // change status of double-clicked keyword
		int idx = list.getSelectedIndex();

		switch(status.get(idx))
		{
		case 0: list.setSelectionBackground(Color.red); // unchecked -> good
			status.set(idx,1);
			count[0]--;
			count[1]++;
			break;
		case 1: list.setSelectionBackground(Color.gray); // good -> bad
			status.set(idx,2);
			count[1]--;
			count[2]++;
			break;
		case 2: list.setSelectionBackground(Color.white); // bad -> unchecked
			status.set(idx,0);
			count[2]--;
			count[0]++;
			break;
		}
		setLabel(l1,1);
		setLabel(l2,2);
		setLabel(l3,0);
	}
		
	private int getKeywordID() { // return keywordID if selected string is a keyword, otherwise -1
		for(int i=0; i< text.keywordNumber; i++)
		{
			if(text.keyword[i].word.equals(termArray[list.getSelectedIndex()]))
				return i;
		}
		return -1;
	}

	public void setFont() //override
	{
		
		list.repaint();
	} 

	@SuppressWarnings("rawtypes")
	class MyCellRenderer extends JLabel implements ListCellRenderer {

		@Override
		public Component getListCellRendererComponent(JList list, Object value,
				int index, boolean isSelected, boolean cellHasFocus) {
			setText(value.toString());
			setOpaque(true);
			setFont(new Font("Dialog",Font.BOLD,getFontSize()));
			try {
				switch(status.get(index))
				{
					case 0: setBackground(Color.white);break;
					case 1: setBackground(Color.red);break;
					case 2: setBackground(Color.gray);break;
				}
				return this;
			} catch (Exception e) {
//				e.printStackTrace();
			}
			return this;
		}
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if(e.getSource() == button1){ // UpdateDic
			try {  // Make csv file
				File sfp = new File(myModulePath+"settings.txt");
				BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(sfp)));
				String defval = br.readLine();
				br.close();
				File fp = new File(myModulePath+outputFileName);
				FileWriter fw = new FileWriter(fp,true);
				for(int i=0; i< termArray.length; i++){
					if(status.get(i)==1){
						fw.write(termArray[i]+defval+termArray[i]+",\"\",\"\""+"\n");
					}
				}
				fw.close(); 
/*				String writeText[] = new String[termArray.length];
				String fname = myModulePath+outputFileName;
				int ln =0;
				for(int i=0;i<termArray.length;i++){
					if(status.get(i)==1){
						writeText[ln++] = termArray[i]+defval+termArray[i]+",,";
					}
				}
				if(ln>0)
					fileWriteArray(fname,writeText,ln); */
			} catch(Exception e1){
				e1.printStackTrace();
			} 
			// add dictionary
			EXECUTE.fileConnect(myModulePath+"AddWords.csv", text.absolutePath+"mecab-ipadic-2.7.0-20070801/TETOriginalNoun.csv", 
					text.absolutePath+"mecab-ipadic-2.7.0-20070801/Noun.csv","EUC-JP");
			createDictionary();
		} else if(e.getSource()== button2){ // ResetDic
			File fp = new File(myModulePath+outputFileName);
			if(fp.exists()){
				fp.delete();
			}
			EXECUTE.filecopy(text.absolutePath+"mecab-ipadic-2.7.0-20070801/TETOriginalNoun.csv", 
					text.absolutePath+"mecab-ipadic-2.7.0-20070801/Noun.csv","EUC-JP");
			createDictionary();
		}
	}

}

