/* $Id: DictionaryRegisterDialog.java 775 2013-10-08 06:14:38Z shayashi $ */
package smart_gs.dictionary;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.awt.geom.Point2D;
import java.util.List;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.xml.parsers.ParserConfigurationException;

import reasoning_web.logical.inter_face.NoWayToShowException;
import smart_gs.logical.Region;
import smart_gs.logical.Spread;
import smart_gs.logical.LineSegment;
import smart_gs.swingui.WorkspaceWindow;
import smart_gs.swingui.toolbar.action.ShowLocalViewAction;
import smart_gs.swingui.toolbar.action.SaveLineSegmentsAndDscCompileAction;
import smart_gs.util.ImageCropper;

public class DictionaryRegisterDialog  extends JDialog{

	private JPanel jContentPane = null;

	protected Region region;

	private JDialog myJDialog;
	
	protected TextField wordTextFiled;
	
	protected JLabel suggestLabel;
	
	
	/**
	 * @param owner
	 */
	public DictionaryRegisterDialog(Frame owner,String title,boolean modal,Region region) {
		super(owner,title,modal);
		this.region = region;
		initialize();
		myJDialog = this;
	}
	private void initialize() {
		this.setSize(400, 250);
		this.setLocationRelativeTo(null); // フレームを画面の中央に表示
		this.setContentPane(getJContentPane());
		
	}

	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(new BorderLayout());
			
			// コンボボックス
			JPanel wordPanel = new JPanel();
			wordPanel.setLayout(new BorderLayout());
			JPanel wordSelectPanel = new JPanel();
			
			wordTextFiled = new TextField(20);
			wordTextFiled.addKeyListener(new KeyListener(){
				public void keyPressed(KeyEvent e) {
					
				}

				public void keyReleased(KeyEvent e) {
					suggestLabel.setText("");
					if(!wordTextFiled.getText().equals("")){
						DictionaryXML dictionaryXML = DictionaryXML.getInstance();
						ArrayList<String> list = dictionaryXML.getWordList(wordTextFiled.getText());
						if(list == null){
							return;
						}
						if(list.size() != 0){
							for(int i=0;i<list.size();i++){
								suggestLabel.setText(list.get(i));
								break;
							}
						}
					}
				}

				public void keyTyped(KeyEvent e) {
					
				}
				
			});
			JLabel wordLabel = new JLabel("Word:");
			wordSelectPanel.add(wordLabel);
			wordSelectPanel.add(wordTextFiled);
			
			JButton dic = new JButton("open dictionary");
			dic.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent arg0) {
					DictionaryDialog dictionaryDialog = new DictionaryDialog(WorkspaceWindow.getInstance(),"Dictionary",true,1);
					dictionaryDialog.setVisible(true);
					if(!dictionaryDialog.isCancel()){
						String word = dictionaryDialog.getCchoiceWord();
						wordTextFiled.setText(word);
						suggestLabel.setText(word);
					}
				}
			});
			wordSelectPanel.add(dic);
			
			
			wordPanel.add(wordSelectPanel,BorderLayout.NORTH);
			suggestLabel = new JLabel("");
			suggestLabel.setHorizontalAlignment(JLabel.CENTER);
			wordPanel.add(suggestLabel,BorderLayout.SOUTH);
			
			
			jContentPane.add(wordPanel, BorderLayout.NORTH);

			try {
				region.setCentermode(true);
				JPanel regionPanel = region.createElementViewPanel();
				jContentPane.add(regionPanel, BorderLayout.CENTER);
			} catch (NoWayToShowException e) {
				e.printStackTrace();
			}

			
			JPanel buttonPanel = new JPanel();
			
			final JCheckBox check = new JCheckBox("Add Line Segment");
			buttonPanel.add(check);
			
			JButton regist = new JButton("Register");
			regist.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent arg0) {
					try{
						String word = suggestLabel.getText();
						if(word.equals("")){
							word = wordTextFiled.getText();
							if(word.equals("")){
								JOptionPane.showMessageDialog(
										WorkspaceWindow.getInstance() , "Don't be not able to register dictionary because word is blank" , "Warning" ,
										JOptionPane.WARNING_MESSAGE);
								return;
							}
						}
						/*
						Image image = new ImageCropper(region).crop();
						ImageIcon icon = new ImageIcon(image);
						try {
							ImageIO.write((BufferedImage)icon.getImage(), "jpeg", new File("test.jpg"));
						} catch (IOException e) {
							// TODO 自動生成された catch ブロック
							e.printStackTrace();
						}
						*/
						DictionaryXML dictionaryXML = DictionaryXML.getInstance();
						dictionaryXML.add(word, region);
						try {
							dictionaryXML.write();
						} catch (ParserConfigurationException e) {
							// TODO 自動生成された catch ブロック
							e.printStackTrace();
						}
						if(check.isSelected()){
						Spread spread = region.getSpread();
						List<Point2D> points = region.getPoints();
						LineSegment line = new LineSegment(spread,points);
						spread.addLineSegment(line);
						SaveLineSegmentsAndDscCompileAction action = new SaveLineSegmentsAndDscCompileAction(spread);
						action.dscCompile();
						}
						
					}finally{
						myJDialog.setVisible(false);
					}
				}
			});
			buttonPanel.add(regist);
			
			JButton cancel = new JButton("Cancel");
			cancel.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent arg0) {
					myJDialog.setVisible(false);
				}
			});
			buttonPanel.add(cancel);

			jContentPane.add(buttonPanel,BorderLayout.SOUTH);			
		}
		return jContentPane;
	}

	
	//Swing - How to widen the drop-down list in a JComboBox
    //http://forums.sun.com/thread.jspa?threadID=570675
    private static class WidePopupMenuListener implements PopupMenuListener{
        private static final int POPUP_MIN_WIDTH = 300;
        private boolean adjusting = false;
        public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
            JComboBox combo = (JComboBox)e.getSource();
            Dimension size  = combo.getSize();
            if(size.width>=POPUP_MIN_WIDTH) return;
            if(!adjusting) {
                adjusting = true;
                combo.setSize(POPUP_MIN_WIDTH, size.height);
                combo.showPopup();
            }
            combo.setSize(size);
            adjusting = false;
        }
        public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {}
        public void popupMenuCanceled(PopupMenuEvent e) {}
    }
	
	
}
