import javax.swing.*;

import java.awt.*;
import java.awt.event.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import java.util.*;
import java.util.List;

import org.ensembl.datamodel.*;
import org.ensembl.driver.*;
import org.ensembl.driver.plugin.standard.*;
/**
 * Description: Demonstrate connection to ENSEMBL database using EnsJ.
 * 
 * @author Bernhard Haubold, Fachhochschule Weihenstephan, Freising, Germany
 * Date: Feb 11, 2004; time: 12:24:21 AM. 
 */
public class EnsemblCore extends JFrame {
	Driver driver;
	JPanel entryPanel;
	JPanel southPanel;
	JPanel outputPanel;
	JPanel chromosomePanel;
	JScrollPane scrollPane;
	JTextField textField;
	JTextField spliceField;
	JTextField chromosomeField;
	JTextArea textArea;
	JLabel label;
	JButton button;
	Connection con = null;

	/**
	 * Sets up the database connection
	 * @param dbName
	 * @param username
	 * @param passwd
	 */

	public EnsemblCore(String dbName, String username, String passwd) {

		try {
			driver =
				new MySQLDriver("141.40.169.175", "hsapiens_core", "student");
		} catch (Exception e) {
			e.printStackTrace();
		}

		con = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			con =
				DriverManager.getConnection(
					"jdbc:mysql://ensembldb.sanger.ac.uk./" + dbName,
					username,
					passwd);
		} catch (Exception e) {
			System.out.println("Connection not found.");
			e.printStackTrace();
		}
		constructGUI();
	}
	// Initialize the graphical user interface
	// Set layout of frame
	private void constructGUI() {
		this.getContentPane().setLayout(new BorderLayout());
		// Construct components of entry panel
		entryPanel = new JPanel();
		entryPanel.setLayout(new BorderLayout());
		label = new JLabel("ENSEMBL Gene-ID:");
		textField = new JTextField("ENSG00000161280");
		// Add tool tip text to text field
		textField.setToolTipText("Enter ENSEMBL identifyer");
		button = new JButton("Find Splices");
		// Construct the text area displaying the query results
		textArea = new JTextArea();
		textArea.setFont(new Font("Courier", 14, 14));
		// Package the text area into a scroll pane
		scrollPane = new JScrollPane(textArea);
		scrollPane.setToolTipText("Query Results");
		//Add southPanel
		southPanel = new JPanel();
		southPanel.setLayout(new BorderLayout());
		// Add outputPanel
		outputPanel = new JPanel();
		outputPanel.setLayout(new GridLayout(1, 2));
		// Add spliceField
		spliceField = new JTextField();
		spliceField.setToolTipText("Splice Results");
		// Add chromosomeField
		chromosomeField = new JTextField();
		chromosomeField.setToolTipText("Gene on Chromosome");
		// Add chromosomePanel
		chromosomePanel = new JPanel(new GridLayout(10, 6));
		// Add action listener to button and text field
		QueryListener queryListener = new QueryListener();
		button.addActionListener(queryListener);
		textField.addActionListener(queryListener);
		// Add the components to the entry panel
		entryPanel.add(label, BorderLayout.WEST);
		entryPanel.add(textField, BorderLayout.CENTER);
		entryPanel.add(button, BorderLayout.EAST);
		southPanel.add(outputPanel, BorderLayout.NORTH);
		southPanel.add(chromosomePanel, BorderLayout.CENTER);
		outputPanel.add(spliceField);
		outputPanel.add(chromosomeField);
		for (int j =1; j<4; j++)
		{
			JLabel titleLabel1;
			titleLabel1 = new JLabel();
			titleLabel1.setFont(new Font("Arial", 14, 12));
			titleLabel1.setText("Chromosome Number");
			chromosomePanel.add(titleLabel1);
			JLabel titleLabel2;
			titleLabel2 = new JLabel();
			titleLabel2.setFont(new Font("Arial", 14, 12));
			titleLabel2.setText("Average Splice Count");
			chromosomePanel.add(titleLabel2);
		}

		String loca;
		for (int i = 1; i < 23; i++) {
			loca = String.valueOf(i);
			chromosomePanel.add(new JLabel("Chromosome " + i));
			chromosomePanel.add(new JTextField(getChromAvg(loca)));
			//chromosomePanel.add(new JTextField(getChromAvg("X"));
			//chromosomePanel.add(new JTextField(getChromAvg("Y"));
		}
		loca = "X";
		chromosomePanel.add(new JLabel("Chromosome X"));
		chromosomePanel.add(new JTextField(getChromAvg(loca)));
		loca = "Y";
		chromosomePanel.add(new JLabel("Chromosome Y"));
		chromosomePanel.add(new JTextField(getChromAvg(loca)));
		chromosomePanel.add(new JLabel("Genome"));
		//chromosomePanel.add(new JTextField("1.3433"));
		chromosomePanel.add(new JTextField(getGenome()));
		chromosomePanel.add(new JLabel("Disease"));
		//chromosomePanel.add(new JTextField("1.5956"));
		chromosomePanel.add(new JTextField(getDisease()));
		chromosomePanel.add(new JLabel("\"Normal\""));
		//chromosomePanel.add(new JTextField("1.3559"));
		chromosomePanel.add(new JTextField(getNormal()));
		chromosomePanel.setToolTipText("Average Transcription Count");

		// Add entry panel to frame
		this.getContentPane().add(entryPanel, BorderLayout.NORTH);
		this.getContentPane().add(scrollPane, BorderLayout.CENTER);
		this.getContentPane().add(southPanel, BorderLayout.SOUTH);
	}

	/**
	 * 
	 */
	private String getNormal() {
		Statement statement = null;
		String queryString;
		ResultSet rs;
		queryString =
			"select avg(transcript_count) from hsapiens_ensemblgene_main where disease_gene is NULL";
		try {
			statement = con.createStatement();
			rs = statement.executeQuery(queryString);
			rs.next();
			return rs.getString(1);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return "";

	}
	public String getDisease() {
		Statement statement = null;
		String queryString;
		ResultSet rs;
		queryString =
			"select avg(transcript_count) from hsapiens_ensemblgene_main where disease_gene is not NULL";
		try {
			statement = con.createStatement();
			rs = statement.executeQuery(queryString);
			rs.next();
			return rs.getString(1);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return "";

	}
	/**
	 * 
	 */
	private String getGenome() {
		Statement statement = null;
		String queryString;
		ResultSet rs;
		queryString =
			"select avg(transcript_count) from hsapiens_ensemblgene_main";
		try {
			statement = con.createStatement();
			rs = statement.executeQuery(queryString);
			rs.next();
			return rs.getString(1);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return "";

	}

	public String getChromAvg(String i) {
		Statement statement = null;
		String queryString;
		ResultSet rs;
		queryString =
			"select avg(transcript_count) from hsapiens_ensemblgene_main where chr_name like '"
				+ i
				+ "'";
		try {
			statement = con.createStatement();
			rs = statement.executeQuery(queryString);
			rs.next();
			return rs.getString(1);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return "";

	}

	public void getGene(String geneName) {
		Gene gene = null;
		List transcripts = null;
		Exon exon;
		Transcript transcript = null;
		Sequence sequence;
		Iterator transcriptIterator;
		String str;
		int countSplice = 0;
		try {
			GeneAdaptor geneAdaptor = driver.getGeneAdaptor();
			gene = geneAdaptor.fetch(geneName);
			if (gene == null) {
				System.out.println("Gene " + geneName + " is null");
			}
			transcripts = gene.getTranscripts();
		} catch (Exception e) {
			textArea.setText("No query result found.");
			spliceField.setText("");
		}

		str = gene.getDescription();
		transcriptIterator = transcripts.iterator();
		while (transcriptIterator.hasNext()) {
			countSplice++;
			transcript = (Transcript) transcriptIterator.next();
			str += "\nSequence:    " + transcript.getSequence().getString();
			str += "\nTranslation: " + transcript.getTranslation().getPeptide();
		}
		textArea.setText(str);
		spliceField.setText("There are " + countSplice + " Splices!");

	}

	public void getChromosome() {
		int start, end;
		String chr;
		chr = textField.getText();
		Statement statement = null;
		String queryString;
		ResultSet rs;
		queryString =
			"select chr_name from hsapiens_ensemblgene_main "
				+ "where gene_stable_id='"
				+ chr
				+ "'";
		try {
			statement = con.createStatement();
			rs = statement.executeQuery(queryString);
			rs.next();
			chromosomeField.setText("Gene is on Chromosome: " + rs.getInt(1));
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public static void main(String[] args) {
		EnsemblCore ensembl =
			new EnsemblCore("ensembl_mart_19_1", "anonymous", "");
		//ensembl.pack();
		ensembl.setTitle("Splice-Varianten");
		ensembl.setSize(new Dimension(800, 700));
		ensembl.setVisible(true);
	}

	class QueryListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			// getGene for splice counting
			getGene(textField.getText());
			// start SQL statement
			getChromosome();
		}
	}
}
