package smart_gs.transcription_tool;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import javax.swing.text.StyleContext;

import smart_gs.logical.Spread;
import smart_gs.spread_selection.SetScopePanel;
import smart_gs.transcription_tool.action.CallTesseractAction;

public class OcrDialog extends JDialog {

	private static final long serialVersionUID = 1L;
	
	private JTextField langSelectField;
	private SetScopePanel scopePanel;
	final private static String DEFAULT_LANG = "eng";
	
	public OcrDialog () {
		super(new JFrame(), "Tesseract OCR");
		
		// lang panel
		JPanel langPanel = new JPanel();
		langPanel.setLayout(new BoxLayout(langPanel, BoxLayout.PAGE_AXIS));
		langPanel.setBorder(new TitledBorder("Language of the text (eng, jpn, deu, etc...)"));
		this.langSelectField = new JTextField("eng");
		this.langSelectField.setFont(new Font(StyleContext.DEFAULT_STYLE,Font.PLAIN,12));
		
		langPanel.add(langSelectField);
		this.add(langPanel, BorderLayout.NORTH);
		
		// scope panel
		this.scopePanel = new SetScopePanel(false);
		this.scopePanel.setBorder(new TitledBorder("Scope to apply OCR"));
		this.add(scopePanel,BorderLayout.CENTER);		
		
		// button panel
		JPanel buttonPanel = new JPanel();
		JButton ok = new JButton("Execute");
		ok.addActionListener(new ExecuteAction());
		buttonPanel.add(ok);
		buttonPanel.add(Box.createRigidArea(new Dimension(20,0)));
		JButton cancel = new JButton("Cancel");
		cancel.addActionListener(new CancelAction());
		buttonPanel.add(cancel);
		this.add(buttonPanel,BorderLayout.SOUTH);
		
		// show dialog
		this.setSize(440, 300);
		this.setLocationRelativeTo(null);
		this.setVisible(true);
		
	}
	
	private class ExecuteAction implements ActionListener{
		public void actionPerformed(ActionEvent e) {
			String lang = langSelectField.getText();
			if(lang == null || lang.length() == 0) {
				lang = DEFAULT_LANG;
			}
			List<Spread> targets = scopePanel.getSpreadsToSearch();
			ActionListener action = new CallTesseractAction(targets, lang, true, true, true);
			action.actionPerformed(e);
			dispose();
		}
	}		
	
	private class CancelAction implements ActionListener{
		public void actionPerformed(ActionEvent e) {
			dispose();
		}
	}	

}
