package action;

import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import org.expasy.sugarconverter.parser.IupacParser;


@SuppressWarnings("serial")
public class TranslationAction extends AbstractAction{
/*
 * When iupac button is selected, iupac sequences in the input area are translated into glycoCT
 */
	
	JPanel jp;
	JTextArea input;
	JRadioButton but;
	
	public TranslationAction(JTextArea input, JPanel jp, JRadioButton but){
		this.input = input;	
		this.jp = jp;
		this.but = but;
	}
	
	public void translate_iupac_to_ct(){
//		get input sequences and split them if there are several sequences
		String out = "";
		String in = input.getText().trim();
		String[] sp_in = in.split("\n\n");
		boolean translated = true;
		

//		for each iupac sequence, check if it's not glycoCT (contains RES) and translate it. If the translation fails, a windows says it
		if (!in.isEmpty() && but.isSelected()){
			for( int i =0; i<sp_in.length; i++){
				System.out.println("sp :  "+ sp_in[i] + "#");
				if (!sp_in[i].isEmpty()){
					if (!sp_in[i].contains("RES")){
						String temp = sp_in[i];
						if (but.getText().equals("IUPAC")){
							IupacParser p= new IupacParser(temp.trim());
							try {

								p.getCtTree(p.parse());
								out = out + sp_in[i] + "\n" + p.getCtSequence() + "\n";
							}
							catch (Exception ex) {
								translated = false;
							}
						}
					}
					else
						out = out + sp_in[i] + "\n";
				}

				out = out + "\n";
			}
			if (translated){
				input.setText(out);
				String text = "Translation from IUPAC to GlycoCT done";
				JOptionPane.showMessageDialog(jp,  text, "Information", JOptionPane.INFORMATION_MESSAGE);			
			}
			else{
				input.setText(in);
				String text = "Translation failed -  input sequences are not in linear IUPAC";
				JOptionPane.showMessageDialog(jp,  text, "Error", JOptionPane.ERROR_MESSAGE);
			}

		}
		
	
//		at the end, input area are constitued by iupac sequences follow by respective glycoCT translation
	}	
	
	@Override
	public void actionPerformed(ActionEvent e) {
			translate_iupac_to_ct();
		}



}