package ITUannotation;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Toolkit;

import javax.swing.JPanel;
import javax.swing.JFrame;
import java.awt.Dimension;
import javax.swing.JButton;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import java.awt.Point;
import javax.swing.JCheckBox;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Scanner;

import javax.swing.SwingConstants;
import javax.swing.filechooser.FileNameExtensionFilter;


//import deneme2.FileDemonstration;


public class Morphological_Analysis_Interface extends JFrame {

	private static final long serialVersionUID = 1L;
	private JPanel jContentPane = null;
	private JButton But_OpenFile = null;
	private JButton But_XML_Translate = null;
	private JButton But_XMLsave = null;
	private JScrollPane jScrollPane = null;
	private JTextArea XMLArea = null;
	private JCheckBox CBox_otoSuggestion = null;
	private ArrayList<PossibleMorphAnalysOfWords> AllWords = new ArrayList<PossibleMorphAnalysOfWords>();  //  @jve:decl-index=0:
	private JLabel labels[] = null;
	private JRadioButton radios[] = null;
	private JPanel panelRadio[] = null;
	private int radioTotalNum = 0;  
	private ButtonGroup groupRadio[] = null;  //  @jve:decl-index=0:
	private  ArrayList<Words> wordsforXML; //  @jve:decl-index=0:
	private Integer labelWidthSize[] =  null;
	private Language lang;
	private JTextField textFields[] = null;
	static public String cpath;
	
	/**
	 * This is the default constructor
	 * @param i 
	 */
	public Morphological_Analysis_Interface(int LangIndex) {
		
		super();
		lang= new Language(LangIndex);
		initialize("");
	}

	/**
	 * This method initializes this
	 * @param string 
	 * 
	 * @return void
	 */
	private void initialize(String filename) {	
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 
		this.setContentPane(getJScrollPane());
		this.setTitle(lang.getLan(1,lang.getLangIndex())+" "+filename);
		this.setSize(screenSize.width, screenSize.height - 50);
}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setPreferredSize(new Dimension(5000, 1000));
			jContentPane.setLayout(null);
			jContentPane.setSize(new Dimension(1900, 600));
			jContentPane.add(getBut_OpenFile(), null);
			jContentPane.add(getBut_XML_Translate(), null);
			jContentPane.add(getBut_XMLsave(), null);
			jContentPane.add(getXMLArea(), null);
			jContentPane.add(getCBox_otoSuggestion(), null);
			
			if(AllWords.size() != 0)
				for(int i = 0; i < labels.length; i++)
				{
					jContentPane.add(labels[i], null);
					jContentPane.add(panelRadio[i], null);
				}
		}
		return jContentPane;
	}

	/**
	 * This method initializes But_OpenFile	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getBut_OpenFile() {
		if (But_OpenFile == null) {
			But_OpenFile = new JButton();
			But_OpenFile.setBounds(new Rectangle(69, 15, 149, 27));
			But_OpenFile.setText(lang.getLan(6, lang.getLangIndex()));
			But_OpenFile.addActionListener(new java.awt.event.ActionListener() {
				

				public void actionPerformed(java.awt.event.ActionEvent e) {
					JOptionPane.showMessageDialog(null, lang.getLan(21, lang.getLangIndex()));
					FileDemonstration application = new FileDemonstration("txt");
					application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
					try
					{	
						File opened = application.getFile(cpath,"txt");
						if(opened == null || opened.isFile()== false)
						{
							JOptionPane.showMessageDialog(null, "File does not exist!");
						}
						else{
						cpath=opened.getParent();
						Syntactic_Analysis_Interface.cpath=cpath;
						convertInputToOutput coto=new convertInputToOutput(opened);
	
					//	Thread.sleep(8000);
							
						File out=coto.getOutputFile();//path);//new File("output2.txt");
						 
						BufferedReader bfr = new BufferedReader(new InputStreamReader
								  (new FileInputStream(out),"UTF8"));
						 
						String outputstr,tempstr ;//="";//
						outputstr="";
						
						
						 while(bfr.ready())
						 {
							 tempstr=bfr.readLine();
							 outputstr=outputstr+"\n"+tempstr;
						 }
							
						 //flRdr.read();
						 String []lines=outputstr.split("\n");
						int line_num=lines.length;
						getJContentPane().setPreferredSize(new Dimension((int)getJContentPane().getPreferredSize().getWidth(),(int)getJContentPane().getPreferredSize().getHeight()+((line_num+10)*getXMLArea().getFont().getSize())));
						int YOfarea;
						if(panelRadio==null)
						{YOfarea=500;}
						else{YOfarea=panelRadio[0].getY()+panelRadio[0].getHeight()+150;}
						
						getXMLArea().setBounds(5,YOfarea,jScrollPane.getHorizontalScrollBar().getMaximum()-5  , (int)getJContentPane().preferredSize().getHeight()-YOfarea/*jScrollPane.getVerticalScrollBar().getMaximum()-330*/);
						 XMLArea.setText(outputstr);
						 XMLArea.repaint();
						 deleteLabels();
						 Parser prs = new Parser(outputstr,"output");
						 ArrayList<String> words = new ArrayList<String>();
						 AllWords = prs.getPossibleMorphofWords(outputstr);//.getWords(outputstr);
						 radioTotalNum = 0;
						 getRadioButtons();  //getRadio labeldan önce olmali label radio verisini kullanıyor
						 getLabels();
							javax.swing.SwingUtilities.invokeLater(new Runnable() {
								   public void run() { 
								      jScrollPane.getVerticalScrollBar().setValue(0);
								   }
								});
						 initialize(opened.getAbsolutePath());
						}
					} 
					catch (IOException e1) 
					{
						e1.printStackTrace();
					} catch (InterruptedException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				
				}
			});
		}
		return But_OpenFile;
	}

	/**
	 * This method initializes But_XML_Translate	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getBut_XML_Translate() {
		if (But_XML_Translate == null) {
			But_XML_Translate = new JButton();
			But_XML_Translate.setBounds(new Rectangle(234, 15, 149, 27));
			But_XML_Translate.setText(lang.getLan(7, lang.getLangIndex()));
			But_XML_Translate.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) 
				{
					String XmL=getXML();				
				}				
			});
			
		}
		return But_XML_Translate;
	}
	private String getXML() {
		int rad_ind=0;
		wordsforXML=new ArrayList<Words>();
		for(int i = 0; i < AllWords.size(); i++)
		{
			for(int j = 0; j < AllWords.get(i).getNumofpossibleexp_ofword()+1; j++)
			{
				if(radios[rad_ind].isSelected())
				{
					Words w = null;
					if(radios[rad_ind].getText().contains(lang.getLan(19, lang.getLangIndex())))
						w=new Words("","",textFields[i].getText(),"",AllWords.get(i).getWordstring());
					else
						w=new Words("","",radios[rad_ind].getText(),"",AllWords.get(i).getWordstring());
					wordsforXML.add( w);//.add(w);
				}
				rad_ind++;		
			}
		}
		XMLCreator xc=new XMLCreator(wordsforXML);
		String XmlStr=xc.getXmlString();
		String []lines=XmlStr.split("\n");
		int line_num=lines.length;
		getJContentPane().setPreferredSize(new Dimension((int)getJContentPane().getPreferredSize().getWidth(),(int)getJContentPane().getPreferredSize().getHeight()+(line_num*10)));
		getXMLArea().setText(XmlStr);
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			   public void run() { 
			      jScrollPane.getVerticalScrollBar().setValue(0);
			   }
			});
		return XmlStr;
	}
	
	
	/**
	 * This method initializes Labels	
	 * 	
	 * @return javax.swing.JLabels	
	 */
	private void getLabels() {
		if (AllWords.size() != 0) {
			 labels = new JLabel[AllWords.size()];
			 int position = 0;
			 for(int i = 0; i < AllWords.size(); i++)
			 {
				 int lastindex=labels.length;
				 int widt=70 + position+labelWidthSize[lastindex-1];
				 getJContentPane().setPreferredSize(new Dimension(widt, (int)getJContentPane().preferredSize().getHeight()));
				 
				 labels[i] = new JLabel(AllWords.get(i).getWordstring());
				 labels[i].setBounds(new Rectangle(40 + position, 75, labelWidthSize[i], 20));
				 labels[i].setBorder(BorderFactory.createLineBorder(Color.black));
				 
				 jContentPane.add(labels[i]);
				 position += labelWidthSize[i];
			 }
		}
		else
			labels = null;
	}
	
	
	/**
	 * This method deletes Labels	
	 * 	
	 * 	
	 */
	private void deleteLabels() {
		if (labels != null) {
			 for(int i = 0; i < AllWords.size(); i++)
			 {
				 labels[i].setBounds(0, 0, 0, 0);
				 panelRadio[i].setBounds(0, 0, 0, 0);
				 textFields[i].setBounds(0, 0, 0, 0);
			 }
		
		labels = null;
		labelWidthSize = null;
		radios = null;
		panelRadio = null;
		radioTotalNum = 0;
		groupRadio = null;
		AllWords = null;
		textFields = null;
		}
	}

	/**
	 * This method initializes Labels	
	 * 	
	 * @return javax.swing.JLabels	
	 */
	private void getRadioButtons() {
		if (AllWords.size() != 0) 
		{
			labelWidthSize = new Integer[AllWords.size()];
			panelRadio = new JPanel[AllWords.size()];
			groupRadio = new ButtonGroup[AllWords.size()];
			textFields = new JTextField[AllWords.size()];
			for(int i = 0; i < AllWords.size(); i++)
			{
				radioTotalNum +=  AllWords.get(i).getNumofpossibleexp_ofword();
			}
			radioTotalNum += AllWords.size();
			int position = 0;
			radios = new JRadioButton[radioTotalNum];
			int k = 0;
			int max = 0;
			for(int i = 0; i < AllWords.size(); i++)
			{
				panelRadio[i] = new JPanel(new GridLayout(AllWords.get(i).getNumofpossibleexp_ofword()+1,1));
				groupRadio[i] = new ButtonGroup();
				for(int j = 0; j < AllWords.get(i).getNumofpossibleexp_ofword(); j++)
				{
					if(j == 0)
						radios[k] = new JRadioButton(AllWords.get(i).getExplanationOftheWord().get(j).getExplanation(), true);
					else
						radios[k] = new JRadioButton(AllWords.get(i).getExplanationOftheWord().get(j).getExplanation(), false);
					radios[k].setName(Integer.toString(k));
					groupRadio[i].add(radios[k]);
					panelRadio[i].add(radios[k]);
					if(radios[k].getText().length() > max)
						max = radios[k].getText().length();		
					k++;
				}
				radios[k] = new JRadioButton(lang.getLan(19, lang.getLangIndex()), false);
				radios[k].setName(Integer.toString(k));
				groupRadio[i].add(radios[k]);
				panelRadio[i].add(radios[k]);
				k++;
				textFields[i] = new JTextField("(1,\"\")");
				textFields[i].setBounds(new Rectangle(40 + position, 430, max * 8 + 10, 20));
				textFields[i].setBorder(BorderFactory.createLineBorder(Color.black));
				panelRadio[i].setBounds(new Rectangle(40 + position, 130, max * 8 + 10, 300));
				panelRadio[i].setBorder(BorderFactory.createTitledBorder((i+1) + ".kelime"));
				jContentPane.add(panelRadio[i]);
				jContentPane.add(textFields[i]);
				position += max * 8 + 10;
				labelWidthSize[i] = new Integer(max * 8 + 10);
				max = 0;
			}
		}
		else
		{
			radios = null;
			panelRadio = null;
		}
	}
		
	
	/**
	 * This method initializes But_XMLsave	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getBut_XMLsave() {
		if (But_XMLsave == null) {
			But_XMLsave = new JButton();
			But_XMLsave.setBounds(new Rectangle(401, 15, 149, 27));
			But_XMLsave.setText(lang.getLan(8, lang.getLangIndex()));
			But_XMLsave.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					JFileChooser chooser = new JFileChooser(cpath);			//only save as a xmlFiles
					FileNameExtensionFilter xmlFilter = new FileNameExtensionFilter("XML files (*.xml)", "xml");
					chooser.addChoosableFileFilter(xmlFilter);
					chooser.setFileFilter(xmlFilter);		    
				    chooser.setAcceptAllFileFilterUsed(false);
				    
					int returnVal = chooser.showSaveDialog(chooser);
					File file = null;
					if (returnVal == JFileChooser.APPROVE_OPTION) {						
						if(chooser.getSelectedFile().getAbsolutePath().endsWith(".xml"))
							file = new File(chooser.getSelectedFile().getAbsolutePath());
						else
							file = new File(chooser.getSelectedFile().getAbsolutePath() + ".xml");
						cpath=file.getParent();
						
						Syntactic_Analysis_Interface.cpath=cpath;
						  try {
							   OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file),"UTF-8");
							   	String OrgnalXml=getXML();//.replaceAll( "\"","&quot;");
								writer.write(OrgnalXml);
								writer.close();
							} catch (IOException e1) {
								e1.printStackTrace();
							}
					}
					else{chooser.setVisible(false);}
					 
						   
					}
				
			});
		}
		return But_XMLsave;
	}

	/**
	 * This method initializes jScrollPane	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getJScrollPane() {
		if (jScrollPane == null) {
			jScrollPane = new JScrollPane();
			jScrollPane.setBorder(null);
			jScrollPane.setViewportView(getJContentPane());
			jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
			jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
			jScrollPane.add(getJContentPane(), null);	
			jScrollPane.setViewportView(jContentPane);

			jScrollPane.getHorizontalScrollBar().addAdjustmentListener(
					new MyAction());

		}
		return jScrollPane;
	}
	public class MyAction implements AdjustmentListener {

		@Override
		public void adjustmentValueChanged(AdjustmentEvent ae) {
			int YOfarea;
			if(panelRadio==null)
			{YOfarea=500;}
			else{YOfarea=panelRadio[0].getY()+panelRadio[0].getHeight()+150;}
			
			getXMLArea().setBounds(5,YOfarea,jScrollPane.getHorizontalScrollBar().getMaximum()-5  , jScrollPane.getVerticalScrollBar().getMaximum()- 390);
			repaint();
		}
	}
	/**
	 * This method initializes XMLArea	
	 * 	
	 * @return javax.swing.JTextArea	
	 */
	private JTextArea getXMLArea() {
		if (XMLArea == null) {
			XMLArea = new JTextArea();
			XMLArea.setBounds(new Rectangle(21, -23, 420, 46));
			XMLArea.setLineWrap(true);
			XMLArea.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
			JScrollPane scrollingResult = new JScrollPane(XMLArea);
			scrollingResult
					.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
			this.add(scrollingResult);
		}
		return XMLArea;
	}

	/**
	 * This method initializes CBox_oto,
	 * 
	 * Suggestion	
	 * 	
	 * @return javax.swing.JCheckBox	
	 */
	private JCheckBox getCBox_otoSuggestion() {
		if (CBox_otoSuggestion == null) {
			CBox_otoSuggestion = new JCheckBox();
			CBox_otoSuggestion.setBounds(new Rectangle(563, 17, 124, 21));
			CBox_otoSuggestion.setText(lang.getLan(9, lang.getLangIndex()));
		}
		return CBox_otoSuggestion;
	}

}  //  @jve:decl-index=0:visual-constraint="7,10"
