package ash.gui.editor.core;
import java.awt.Font;
import static java.awt.Font.*;
import javax.swing.JFrame;
import javax.swing.JDialog;
import javax.swing.JButton;
import javax.swing.JComboBox;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import ash.gui.core.AshGroupPanel;
import ash.gui.core.AshFont;

/**
 * フォント設定ダイアログ
 */
@SuppressWarnings("serial")
public class AshFontPanel extends AshGroupPanel implements ActionListener {
	public static Font updateFont(JFrame frame, Font font) {
		JDialog dialog = new JDialog(frame, "フォント選択", true);
		AshFontPanel fp = new AshFontPanel(dialog, font);
		dialog.setContentPane(fp);
		//dialog.setResizable(false);
		dialog.pack();
		dialog.setLocationRelativeTo(frame);	// ウィンドウを中央に配置
		dialog.setVisible(true);
		dialog.dispose();
		return (fp.createdFont != null) ? fp.createdFont : font;
	}

	static private String[] styleList = { "標準", "太字", "斜体", "太字 斜体" };
	static private Integer[] sizeList = { 10,12,14, 16, 18, 20, 22, 24, 26, 28 };
	static private int[] fontStyles = { PLAIN, BOLD, ITALIC, ITALIC | BOLD };
	private JComboBox fontCombo  = combobox(AshFont.nameList);
	private JComboBox styleCombo = combobox(styleList);
	private JComboBox sizeCombo  = combobox(sizeList);
	private JButton ok, cancel;
	private JDialog dialog;
	private Font createdFont = null;

	AshFontPanel(JDialog dialog, Font font) {
		this.dialog = dialog;
		fontCombo.setSelectedItem(font.getName());
		styleCombo.setSelectedIndex(findStyleIndex(font.getStyle()));
		sizeCombo.setSelectedItem(font.getSize());
		setActionListener(this);
		ok = button("了解");
		cancel = button("取消し");
		//           フォント属性を選択してください。
		// 書体名    [                        ] ▼
		// スタイル  [                ] ▼
		// サイズ    [        ] ▼
		//           (了解)    (取消し)
		form(line(null,       "フォント属性を選択してください。"),
			 line("書体名",   fontCombo),
			 line("スタイル", sg(styleCombo, gap(40))),
			 line("サイズ",   sg(sizeCombo, gap(80))),
			 line(null,       sg(ok, gap(20), cancel, gap(20))));
	}
	// ボタンイベントでダイアログを閉じる
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == ok) {
			String fontName = AshFont.nameList[fontCombo.getSelectedIndex()];
			int fontStyle = fontStyles[styleCombo.getSelectedIndex()];
			int fontSize = sizeList[sizeCombo.getSelectedIndex()];
			createdFont = new Font(fontName, fontStyle, fontSize);
		}
		dialog.dispose();
	}
	private int findStyleIndex(int fontStyle) {
		for(int i = 0; i < fontStyles.length; i++) {
			if(fontStyles[i] == fontStyle) return i;
		}
		return 0;
	}
}
