package asandatabasebrowser.view;

import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.text.BadLocationException;

import net.sourceforge.swingx.SxUtilities;
import asandatabasebrowser.AsanDatabaseBrowser;
import asandatabasebrowser.Global;

public class SqlLogView extends JFrame {
	JTextArea area = new JTextArea();
	public SqlLogView() {
		super("SQLログ");
		setIconImage(Global.getImage("/resources/Log.png"));
		area.setEditable(false);
		area.setFont(AsanDatabaseBrowser.theApp.doc.getFont());
		area.setToolTipText("この内容は、AsanDatabaseBrowser.log にも出力されています。");
		area.addMouseListener(new TextComponentMouseListener());
		//SxUtilities.addPopupMenuMouseListener(area);
		getContentPane().add(new JScrollPane(area));
		setLocation(0, 600);
		setSize(640, 240);
		//setVisible(true);
	}
	public void append(String str) {
		area.append(str);
		// 自動的にスクロールさせる。
		if (isVisible()) {
			try {
				int pos = area.getText().length();
				Rectangle rect = area.modelToView(pos);
				area.scrollRectToVisible(rect);
				//System.out.println("pos="+pos+" rect="+rect);
			} catch (BadLocationException e) {
				e.printStackTrace();
			} 
		}
	}
	void clear() {
		area.setText("");
	}
	class TextComponentMouseListener extends MouseAdapter {
		public void mousePressed(MouseEvent ev) {
			if (ev.isPopupTrigger()) {
				showPopupMenu(ev);
			}
		}
		public void mouseReleased(MouseEvent ev) {
			if (ev.isPopupTrigger()) {
				showPopupMenu(ev);
			}
		}
		private void showPopupMenu(MouseEvent ev) {
			JPopupMenu popup = new JPopupMenu();
			SxUtilities.addMenuItems(area, popup);
			popup.addSeparator();
			popup.add(new ClearAction());
			popup.show(area, ev.getX(), ev.getY());
		}
	}	
	class ClearAction extends AbstractAction {
		ClearAction() {
			super("クリア(C)");
			putValue(MNEMONIC_KEY, new Integer('C'));
			putValue(SHORT_DESCRIPTION, "クリア");
			putValue(LONG_DESCRIPTION, "ログをクリアする");
		}
		public void actionPerformed(ActionEvent e) {
			clear();
		}
	}
}
